我正在处理链表..我成功插入并删除了第一个节点的节点..但是当我尝试最后插入节点时...它给出了一个错误“对象引用未设置为对象的实例”
我的逻辑是正确的,但视觉工作室正在产生一个例外,不知道为什么 请帮帮我..
完整代码如下
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();
}
}
答案 0 :(得分:2)
基本上你必须处理一个空列表的情况。在列表为空的当前代码中,您的上一个,当前和第一个都等于null
。因此,当您尝试在前一个等于previous.next()
时为null
分配值时,您会收到错误消息。
答案 1 :(得分:0)
如果列表为空,则首先将等于null,并且当您尝试执行此操作时,您的代码将引发异常previous.next = newNode;
,因为previous
也是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;
}
编辑:你可以像这样实现它,但是如果第一个是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;
}
}
}