Maximillan
Maximillan

Reputation: 59

Removing a node from a singly linked list

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

Answers (2)

thyago stall
thyago stall

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

sisyphus
sisyphus

Reputation: 6392

You need to set previous.next to current.next when you find the node.

Upvotes: 3

Related Questions