【问题标题】:Remove from single linked list via index通过索引从单链表中删除
【发布时间】:2016-02-08 21:43:19
【问题描述】:

如何在不使用tail的情况下通过索引插入通用链表。

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 列表数组。我不知道为什么当我给他第一个索引时它总是删除我 5,15。

【问题讨论】:

  • 当您实际从列表中删除时,为什么标题会显示“添加”?
  • 已编辑,抱歉,今天的代码太多了。

标签: c# generics collections linked-list


【解决方案1】:

第一次迭代 (count = 0) => else 块被执行 => current = current.next => current = 10, current.next = 15

第二次迭代 (count=1) => if 块被执行 => current.next = null => 15 被删除 => 当前 = 10

在第二次迭代结束时 count = 2 并退出 while 循环 => Head = current => Head = 10 => 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++;
   }       
} 

【讨论】:

    【解决方案2】:
    var list1 = new LinkedList<int>();
    
    var nodesToRemove = list1.Where(x => x == index).ToList();
    
    foreach(var node in nodesToRemove)
            lis1.Remove(node);
    

    【讨论】:

    • 谢谢,但是我正在从 scatch 制作单链表,具有泛型类型并使用 Head。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2014-08-23
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多