2012-12-30 204 views
-3

我想從鏈接列表中刪除節點!我的鏈表中存儲了以下數據。從鏈接列表中刪除節點

aa 1 1 1 1 
bb 2 2 2 2 
cc 3 3 3 3 

我使用的Java代碼和我的代碼是

Node p=first; 

for(Node c=first;c!=null;c=c.next){ 

    if(c.data.startsWith(key)){ 
     if(c.next==null){ 

     } 
     else{ 
      p=c; 
     } 

     if(c==first){ 
      first=first.next; 
     } 
     else{ 
      p.next=c.next; 
     } 
    } 
} 

我得到的一個問題,這個代碼僅刪除數據即CC 3 3 3 3正確。我想這是什麼問題在我的代碼,以便我能夠刪除我想刪除的數據! 在此先感謝。

+1

我......不明白?問題是什麼? – Doorknob

+3

下面是一個可以幫助你解決這個問題的魔術:http://en.wikipedia.org/wiki/Debugger – Isaac

+0

如何定義鏈表以及如何在其中存儲數據? –

回答

1

你需要這個作爲你的循環的最後一行:

p = c; 

您還需要消除對是否c.next == null測試。找到密鑰時刪除節點並不重要。

整個循環應該是:

for(Node c = first, p = null; c != null; p = c, c = c.next){ 

    if (c.data.startsWith(key)) { 
     if (p == null) { 
      first = c.next; 
     } else { 
      p.next = c.next; 
     } 
     break; 
    } 
    p = c; 
} 
+0

現在,它只會一直刪除最後一個節點,而不檢查密鑰 –

+0

@JunaidHassan - 糟糕。更新我的示例代碼。 –

0

你不應該需要的這段代碼:

if(c==first){ 
     first=first.next; 
    } 
    else{ 
     p.next=c.next; 
    } 

你的循環已經移動到下一個節點。此代碼只會導致您跳過其他每個節點。也許這就是爲什麼你沒有找到鑰匙。

+0

它仍然不工作,我已經刪除了你問我的代碼,但問題是,我的代碼只刪除最後一個節點,但我需要刪除節點,我希望在關鍵的幫助下通過 –

+0

那是因爲你只設置了p如果它不是從鍵開始的,這意味着你總是會刪除最後一個不匹配鍵的節點。您想在if塊(而不是else塊)中設置p,以便p保持設置爲與密鑰 –

+0

匹配的節點並將p初始化爲NULL。在循環結束時,p將爲NULL或將指向與鍵匹配的節點 –

0

試試這樣說:

Node lastNode = null; 

// Traverse all nodes in the list 
for (Node node = first; node != null; node = node.next) { 

    // Check for node to delete 
    if (node.data.startsWith(key)) { 
     if (lastNode != null) { 
      // directly link last node with next node to remove node 
      lastNode.next = node.next; 
     } else { 
      // if the node to delete is the first node, update first node 
      first = node.next; 
     } 
     // remember last node 
     lastNode = node; 
    } 
}