1

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
}
MinaHany
  • 1,015
  • 4
  • 16
  • 32

3 Answers3

6

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.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • +1 for explaining **why** it doesn't work. You beat me to it by just a hair! – Zéychin Jul 16 '13 at 13:03
  • 1
    Why does n.next= null work? Wouldn't that be changing the n local to the method as well? – MinaHany Jul 16 '13 at 13:49
  • 1
    The object that `n` points to is shared with the caller. See http://stackoverflow.com/questions/40480/is-java-pass-by-reference – Joni Jul 16 '13 at 13:54
2

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;
}
morgano
  • 17,210
  • 10
  • 45
  • 56
1

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.

kiheru
  • 6,588
  • 25
  • 31