我想知道該功能如何在嘗試從單獨鏈接列表中刪除節點時獲取根節點。我瞭解整個刪除部分。如何從單個鏈接列表中刪除根節點
class LinkedList {
LinkedListNode root;
// Remove the nodes which contain data equal to obj
void deleteNode(Object obj) {
// special case for root
if(root.data.equals(obj)) {
root = root.next;
}
LinkedListNode current = root;
// iterate through list looking for obj
while(current.next != null) {
// match found
if(current.next.data.equals(obj)) {
// cut out the node
current.next = current.next.next;
}
current = current.next;
}
}
}
private class LinkedListNode {
Object data;
LinkedListNode next;
}
我不知道爲什麼只是通過創建一個LinkedListNode根,它指的是根節點。清楚和容易理解的幫助將不勝感激。
從理論上講,我沒有創建LinkedListNode根,我可以傳入一個額外的參數給刪除函數,並根據其數據指定哪一個是頭部?
LinkedListNode deleteNode(LinkedListNode head, int d) {
LinkedListNode n = head;
if (n.data == d) {
return head.next; /* moved head */
}
while (n.next != null) {
if (n.next.data == d) {
n.next = n.next.next;
return head; /* head didn’t change */
}
n = n.next;
}
}
你能向我解釋一下如何初始化根節點嗎?謝謝=) – Sasha 2011-05-08 23:02:49
你可能會想用一個構造函數來做到這一點,這是初始化類的成員變量的標準方法。看看這個MSDN頁面,它提供了所有的細節:http://msdn.microsoft.com/en-us/library/ms173115.aspx 在你的情況,你需要初始化root用類似' root = new LinkedListNode'並提供初始的'data'和'next'值 – kaveman 2011-05-09 05:04:03