我正在鏈接列表..我成功插入和刪除節點在第一個節點..但是當我嘗試插入節點在最後..它給出了一個錯誤「對象引用未設置到對象」插入最後節點單鏈表
我的邏輯是正確的,但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();
}
}
「我的邏輯是正確的,但視覺工作室正在產生一個異常」 - 不,你的邏輯是錯誤的,你的代碼導致異常 - 不要責怪你的工具! – tomfanning