2016-05-14 38 views
-1

这是我在删除具有给定节点值的节点之前删除节点的方法,但它不起作用,我该怎么办。例如,1到5,把RemoveBefore(3),它会删除4.链接列表方法,在具有给定节点值的节点之前移除节点

public void RemoveBefore(int nodeValue) 
{ 
    Node curr = start; 

    while (curr != null) 
    { 
     Node next = curr.next; 

     if (next!= null && next.nodeValue == nodeValue) 
     {     
      curr= next.next;     
      return; 
     } 
     curr = curr.next; 

    } 
} 
+1

如果你写了这段代码,你就足够回答你的问题了自。 – Dici

回答

0

修改的curr值像你这样:

curr= next.next; 

将不会更改列表本身,因为curr只是一个本地引用,改变引用不会改变它指向的内容。

如果您希望更改生效,您需要修改引用指向的对象的内容。

在你的情况的情况如下:

... -> prev -> curr -> next -> next.next -> ... 

如果next有你的价值,你想prev直接指向next,其实从列表中像这样除去curr

... -> prev -> next -> next.next -> ... 

这意味着您要更改prev,因此它指向next而不是curr

因此,在你的代码,你需要引入prev变量并管理的特殊情况时,删除的节点是启动本身:

startNode -> node2 -> node3 -> ... 

有可能成为:

node2 (the new start node) -> node3 -> ... 

这是我如何修改代码:

public void RemoveBefore(int nodeValue) 
{ 
    Node curr = start; 
    Node previous = null; 

    while (curr != null) 
    { 
     Node next = curr.next; 

     if (next!= null && next.nodeValue == nodeValue) 
     {     
      if(previous == null) { 
       start = next;   // change directly the start of the list 
      } else { 
       previous.next = next; // point to next instead of curr 
      } 
      return; 
     } 
     previous = curr; 
     curr = curr.next; 
    } 
} 
+0

但是当我改变了,没有发生,当我跑步。 – Kevin

+0

是的,我纠正了我的答案 –