我正在链接列表..我成功插入和删除节点在第一个节点..但是当我尝试插入节点在最后..它给出了一个错误“对象引用未设置到对象”插入最后节点单链表
我的逻辑是正确的,但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