Kevin Kevin - 6 months ago 12
Java Question

Linked List method that removes the node before the node having the given node value

This is my method to remove the node before the node having the given node value, but it is not work, how can i do. For example, 1 to 5, put RemoveBefore(3), it will remove 4.

public void RemoveBefore(int nodeValue)
{
Node curr = start;

while (curr != null)
{
Node next = curr.next;

if (next!= null && next.nodeValue == nodeValue)
{
curr= next.next;
return;
}
curr = curr.next;

}
}

Answer

Modifying the value of curr like you did:

curr= next.next;

will make no changes to the list itself because curr is a just a local reference, changing the reference will not change the content pointed by it.

If you want your changes to have effect you need to modify the content of the object pointed by the reference.

In your case the situation is the following:

... -> prev -> curr -> next -> next.next -> ...

If next has your value, you want prev to point directly to next, in fact removing curr from the list like so:

... -> prev -> next -> next.next -> ...

This means you want to change prev so it point to next instead of curr.

So in your code you need to introduce the prev variable and also manage the special case when the node to remove is the start itself:

startNode -> node2 -> node3 -> ...

has to become:

node2 (the new start node) -> node3 -> ...

This is how I would modify the code:

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;
    }
}