从链接列表中删除第一个

时间:2014-11-11 20:33:42

标签: c#

我想在我的链接列表中删除我的第一个值但是我不确定我的代码是否正确我的删除最后工作正常但我的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但我不确定这是否正确

1 个答案:

答案 0 :(得分:1)

此代码:

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。

快速说明;你应该删除" RemoveFirst"和#34; RemoveLast"来自您的Node类。这些是列表的功能;不是节点。

如果你把所有方法放在list类中(你应该这样做!),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;
}