我写了一段代码,应该删除单链表中的一个节点。但它根本不起作用,即它打印原始列表而不删除任何内容。我做错了什么?假设列表不为空!
public void removeNode(int data){
Node current = head;
Node previous = null;
while(current != null && current.data != data){
previous = current;
current = current.next;
}
previous = current.next;
}
找到节点时,需要将previous.next设置为current.next。
只需尝试正确设置指针即可。类似:
public void removeNode(int data) {
Node current = head;
Node previous = null;
while (current != null && current.data != data) {
previous = current;
current = current.next;
}
if (current != null) {
previous.next = current.next
}
}