0

我正在处理链表..我在第一个节点上成功插入和删除了一个节点..但是当我最后尝试插入节点时..它给出一个错误“对象引用未设置为对象的实例”

我的逻辑是正确的,但是 Visual Studio 正在生成一个异常,不知道为什么请帮帮我..

完整代码如下

class MyList
{
    private Node first;
    private Node current;
    private Node previous;

    public MyList()
    {
        first = null;
        current = null;
        previous = null;
    }

    public void InsertLast(int data)
    {
        Node newNode = new Node(data);

        current = first;

        while (current != null)
        {
            previous = current;
            current = current.next;
        }

        previous.next = newNode;
        newNode.next = null;
    }

    public void displayList()
    {
        Console.WriteLine("List (First --> Last): ");
        Node current = first;
        while (current != null)
        {
            current.DisplayNode();
            current = current.next;
        }
        Console.WriteLine(" ");
    }
}



class Node
{
    public int info;
    public Node next;

    public Node(int a)
    {
        info = a;
    }

    public void DisplayNode()
    {
        Console.WriteLine(info);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyList newList = new MyList();

        newList.InsertLast(10);
        newList.InsertLast(20);
        newList.InsertLast(30);
        newList.InsertLast(40);

        newList.displayList();

        Console.ReadLine();
    }
}
4

2 回答 2

2

基本上你将不得不处理一个空列表的情况。在您当前的代码中,当列表为空时,您的上一个、当前和第一个都等于null. 所以你得到一个错误,因为你试图previous.next()在之前的 equals 时分配一个值null

于 2012-12-03T14:40:01.010 回答
0

如果列表为空,则 first 将等于 null 并且当您尝试执行此操作时您的代码将引发异常,previous.next = newNode;因为previousis 也是null. 添加第一个节点时,您必须首先添加新元素,因此重写代码如下:

public void InsertLast(int data)
{
      Node newNode = new Node(data);
      if (first == null)
      {
           first = newNode;
      }
      else
      {
           current = first;

           while (current != null)
           {
                previous = current;
                current = current.next;
           }
           previous.next = newNode;
      }
      newNode.next = null;
}

编辑:您可以像这样实现它,但要注意拳头是否为空以及只有第一个节点的情况。检查方法:

public void RemoveLast()
{            
      if (first != null)//there is no point in removing since the list is empty
      {
           if (first.next == null) //situation where list contains only one node
                first = null;
           else //all other situations
           {
                current = first;

                while (current.next != null)
                {
                    previous = current;
                    current = current.next;
                }
                previous.next = null;
           }
      }
}
于 2012-12-03T14:33:24.033 回答