我有一個雙重鏈接列表和我應該刪除給定節點的方法。它最初與我的3個測試節點一起工作,當我最初開發代碼時,但是當我向雙鏈表添加更多節點時,它停止工作,現在我得到一個NullReferenceException:「對象引用未設置爲對象的實例」我知道我可以使用通用鏈表,但我想了解雙鏈表如何工作。在從雙向鏈表中刪除節點時遇到問題
我將在代碼中標記行,我在行的開頭使用「**」(它位於雙鏈表類的RemoveNode方法中)獲取此異常。
這裏是我的代碼:
雙向鏈表類:
class DoublyLinkedList
{
public Node head, current;
public void AddNode(object n) // add a new node
{
if (head == null)
{
head = new Node(n); //head is pointed to the 1st node in list
current = head;
}
else
{
while (current.next != null)
{
current = current.next;
}
current.next = new Node(n, current); //current is pointed to the newly added node
}
}
public Node FindNode(object n) //Find a given node in the DLL
{
current = head;
while ((current != null) && (current.data != n))
current = current.next;
if (current == null)
return null;
else
return current;
}
public string RemoveNode(object n)//remove nodes
{
String Output = "";
if (head == null)
{
Output += "\r\nLink list is empty";
}
else
{
current = FindNode(n);
if (current == null)
{
Output += "Node not found in Doubly Linked List\r\n";
}
else
{
****current.next.prev = current.prev;**
current.prev.next = current.next;
current.prev = null;
current.next = null;
Output += "Node removed from Doubly Linked List\r\n";
}
}
return Output;
}
public String PrintNode() // print nodes
{
String Output = "";
Node printNode = head;
if (printNode != null)
{
while (printNode != null)
{
Output += printNode.data.ToString() + "\r\n";
printNode = printNode.next;
}
}
else
{
Output += "No items in Doubly Linked List";
}
return Output;
}
}
Node類:
class Node
{
public Node prev, next; // to store the links
public object data; // to store the data in a node
public Node()
{
this.prev = null;
this.next = null;
}
public Node(object data)
{
this.data = data;
this.prev = null;
this.next = null;
}
public Node(object data, Node prev)
{
this.data = data;
this.prev = prev;
this.next = null;
}
public Node(object data, Node prev, Node next)
{
this.data = data;
this.prev = prev;
this.next = next;
}
}
'current'不應該是您的列表中的成員。它應該是適當方法的局部變量。 –
看起來像'current.next'必須爲空。發生此異常時,是否刪除列表中的最後一項? – Blorgbeard
請不要包含關於問題標題中使用的語言的信息,除非在沒有它的情況下沒有意義。標籤用於此目的。 –