修改的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;
}
}
如果你写了这段代码,你就足够回答你的问题了自。 – Dici