从链表中删除第一个

本文关键字:第一个 删除 链表 | 更新日期: 2023-09-27 18:30:00

我正在尝试删除链表y中的第一个值,但我不确定我的代码是否正确,我的Remove-last工作正常,但我的removeFirst不正常。

 public class IntegerLinkedList
    {
        private class Node
        {
            public int value;
            public Node next;

            public Node(int v)
            {
                value = v;
                next = null;
            }
            internal int removeLast()
            {
                int value;
                if (next.next == null)
                {
                    value = next.value;
                    next = null;
                    return value;
                }
                else
                    return next.removeLast();
            }
            internal int removeFirst()
            {
                int value;
                if (next.next != null)
                {
                    value = next.value;
                    next = null;
                    return value;
                }
                else
                    return next.removeFirst();

            }
        }

        int count;
        Node start;

这是我的removeFirst 代码

public int removeFirst()
{
    int value;

 if  (start.next != null)
    {
        value = start.value;
    }
    else
        value = start.removeFirst();
    return value;
}

}

这是我的链接列表

IntegerLinkedList myList = new IntegerLinkedList();
                myList.addFirst(1);
                myList.addFirst(2);
                myList.addFirst(3);
                myList.addFirst(4);

                Console.WriteLine(" expect to 4  to be removed" + myList.removeFirst());
}

它显示

删除了4,但我不确定这是否正确

从链表中删除第一个

此代码:

internal int removeFirst()
{
   int value;
   if (next.next != null)
   {
      value = next.value;
      next = null;
      return value;
   }
   else
      return next.removeFirst();
}

将递归遍历列表并截断最后一个元素。它实际上与removeLast相同。

相反,你只需要做这样的事情:

Node currentStart = start;
start = start.next;
return currentStart.value;

"启动"Node对象不应该再有任何指向它的引用,因此它将是GCd。

速记;您可能应该从Node类中删除"RemoveFirst"answers"RemoveLast"。这些都是清单的功能;而不是节点。

如果你把所有的方法都放在列表类中(你应该这样做!),addFirst(应该是addFirst)将是:

public void AddFirst(int item)
{
   Node newNode = new Node();
   newNode.value = item;
   newNode.next = start;
   start = newNode;
}

您的addLast需要迭代(或者您可以选择跟踪"尾部"节点):

public void AddLast(int item)
{
   Node newNode = new Node();
   newNode.value = item;
   Node tailNode = start;
   while (tailNode.next != null)
      tailNode = tailNode.next;
   //In C++ you could cheat and do: while (tailNode = tailNode.next != null);
   //Tail node is now at the end
   tailNode.next = newNode;
}