我编写的代码应该删除单链表中的节点。但它根本不工作,即它打印原始列表而不删除任何东西。我做错了什么 ?假设列表不为空!
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;
}
答案 0 :(得分:3)
找到节点时,需要将previous.next设置为current.next。
答案 1 :(得分:1)
尝试正确设置指针。像:
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
}
}