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()前の値が等しいときに値を割り当てようとしているため、エラーが発生していますnull

于 2012-12-03T14:40:01.010 に答える
0

リストが空の場合、firstはnullに等しくなり、これを実行しようとするとコードで例外が発生します。これは、もでprevious.next = newNode;あるためです。最初のノードを追加するときは、最初に新しい要素を追加する必要があるため、次のようにコードを書き直します。previousnull

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;
}

編集:あなたはそれをこのように実装することができますが、最初が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 に答える