DewinDell
DewinDell

Reputation: 1028

Setting myself to null - Java

I came across the following problem:

Delete a node in the middle of a singly linked list, given only access to that node. (head is not given) Now there are a lot of solutions and they all do not work when the element to be deleted is the last node.

Why wouldn't this work?

public static void removeNode (Node n){
    if(n.next == null){ //n is the last node
        n= null;
        return;
    }
    //handling general case here
}

Upvotes: 1

Views: 139

Answers (3)

kiheru
kiheru

Reputation: 6618

n is local to the method, so changing its value won't affect the list itself. You need to modify the next of the previous node, which you do not have access to.

Upvotes: 1

Joni
Joni

Reputation: 111349

Java passes parameters by value, so setting n to null has no effect outside of the method. This means the method essentially does nothing when passed the last node of a list.

Upvotes: 6

morgano
morgano

Reputation: 17422

You need to set null the reference in the previous node, not the variable that references to your last node, something like this:

if(n.next == null) {
    prev.next = null;
    return;
}

Upvotes: 2

Related Questions