Reputation: 59
I've written a code that should remove a node in a singly linked list. But it's not working at all, i.e. it prints the original list without removing anything. What did I do wrong ? Assume that a list is not empty!
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;
}
Upvotes: 3
Views: 107
Reputation: 1704
Just try to set the pointers correctly. Like:
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
}
}
Upvotes: 1
Reputation: 6392
You need to set previous.next to current.next when you find the node.
Upvotes: 3