class ListNode
{
public object Data { get; private set; }
public ListNode Next { get; set; }
public ListNode(object Element)
{
Data = Element;
}
public ListNode(object Element, ListNode NextNode)
{
Data = Element;
Next = NextNode;
}
public ListNode()
{
}
}
class LinkedList
{
ListNode first;
ListNode last;
public LinkedList()
{
first = null;
last = null;
}
public ListNode Find(object After)
{
ListNode current = new ListNode();
current= first;
while (current.Data != After)
current = current.Next;
return current;
}
public void Add(object newItem, object After)
{
ListNode current=new ListNode();
ListNode newNode=new ListNode();
current = Find(After);
newNode.Next = current.Next;
current.Next = newNode;
}
public void InsertAtFront(object Element)
{
if (IsEmpty())
{
first = last = new ListNode(Element);
}
else
{
first = new ListNode(Element,first);
}
}
bool IsEmpty()
{
return first == null;
}
public void Display()
{
ListNode current = first;
while (current!=null)
{
Console.WriteLine(current.Data);
current = current.Next;
}
}
}
我为Add After特定元素实现了Find方法,但是当我调试它时,显示对象引用未设置为对象异常的实例。请在Find方法或Add After方法中指出我的错误。感谢
答案 0 :(得分:3)
current= first;
while (current.Data != After)
可能会导致潜在的空引用问题。 first仍然可以从构造函数初始化设置为null,这意味着current = null,然后会导致null.Data,这将抛出空引用异常。
这将修复Find()
中的空引用问题 while (current != null && current.Data != After)
修复此问题会导致返回null,这仍然会导致Add
current = Find(After);
newNode.Next = current.Next;
current.Next = newNode;
在此上下文中,LinkedList
首先被初始化,current = Find(After)
将表示current = null,在接下来的两行中导致另一个空引用异常。
public void Add(object newItem, object After)
{
if (IsEmpty())
{
InsertAtFront(newItem);
return;
}
ListNode newNode = new ListNode();
ListNode current = Find(After);
newNode.Next = current.Next;
current.Next = newNode;
}
这将修复Add
和Find
方法,以便以下列形式使用:
LinkedList list = new LinkedList();
list.InsertAtFront("test");
list.Find(list.first.Data);
list.Add("test2", ll.first.Data);
这将使其可行,但我强烈建议您阅读链接列表的实现或使用其中一个系统集合,因为此实现具有相当多的潜在问题。
答案 1 :(得分:2)
问题在这里
while (current.Data != After)
current = current.Next;
如果列表中没有After,您最终会current.Next
等于null
您需要检查current.Next是否为空
while (current.Next != null && current.Data != After)
current = current.Next;
您还应修复添加逻辑(如果要将元素添加到空列表中)
public void Add(object newItem, object After)
{
if(IsEmpty())
{
InsertAtFront(newItem);
return;
}
ListNode newNode=new ListNode();
newNode.Data = newItem;
ListNode current = Find(After);
newNode.Next = current.Next;
current.Next = newNode;
}