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;
}
}
}
我實現Find方法後添加特定的元素,但當我調試它顯示我的對象引用未設置爲對象異常的實例。請在Find方法或Add After方法中指出我的錯誤。謝謝如何在方法在鏈接列表中工作後添加?
作業?如果沒有,只需使用'List
您可能想要考慮擺脫一些不需要的'ListNode'初始化。即改變'current = Find(After);' 爲'ListNode current = Find(After);'which'd允許你擺脫'ListNode current = new ListNode();'等 –