通过索引从单个链接列表中删除

时间:2016-02-08 21:43:20

标签: c# generics collections linked-list

如何通过索引插入到通用链表而不使用尾部。

public void RemoveByIndex(int index)
{
    int count = 0;
    LinkedListNode<T> current = Head;
    while (count <= index)
    {
        if (count == index)
        {
            current.Next = null;
        }
        else
        {
            current = current.Next;
        }
        count++;
    }
    Head = current;
}

我有数据5,10,15的int list数组。我不知道为什么当我给他第1个索引时它总是删除我5,15。

2 个答案:

答案 0 :(得分:0)

args

答案 1 :(得分:0)

第一次迭代(count = 0)=&gt; else阻止执行=&gt; current = current.next =&gt; current = 10,current.next = 15

第二次迭代(count = 1)=&gt; if阻止执行=&gt; current.next = null =&gt; 15被删除=&gt; current = 10

在第二次迭代结束时count = 2并退出while循环=&gt; Head = current =&gt;头= 10 =&gt; 5被删除

可能的解决方案:

public void RemoveByIndex(int index)
{
   int count = 0;
   LinkedListNode<T> current = Head;
   LinkedListNode<T> previous = current;
   while (count <= index)
   {
       if (count == index)
       {
           previous.next = current.next               
           current = null;               
       }
       else
       {
           previous = current;
           current = current.Next;
       }           
       count++;
   }       
}