2012-12-30 206 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; 
    } 
}