0

In C this concept becomes beautifully clear with pointers but im having trouble understanding what exactly is going on here in java.

Can someone please explain to me how come when i traverse the list in removeNode(), it doesnt change any thing on the original object BUT when i do front.next = front.next.next it actually changes the object. Its driving me crazy cause in C i can just use pointers to edit w/e i want. What exactly is going on here with the references?

Note: I know this code doesnt handle edge cases. like null nodes, etc...

public class LLnode{
    int value;
    LLnode next;

    public LLnode(int x){
        this.value = x;
        this.next = NULL;
    }
}

/*
 * This fn removes the node with the specified value n from the linked list
 */
public void removeNode(LLnode head, int n){
    LLnode front = head;
    while (front.next.value != n){
        front = front.next;  //why DOESN'T this physically change the LL?
    }
    front.next = front.next.next;  //why DOES this physically change the LL ?
}
public static void main(String[] args){
    //node creation
    LLnode a = new LLnode(10);
    LLnode b = new LLnode(20);
    LLnode c = new LLnode(30);
    LLnode d = new LLnode(40);

    //assignments
    c.next = d;
    b.next = c;
    a.next = b;

    removeNode(a,30);

}

Thanks.

  • `front = front.next;` - that's just changing a local variable `front` so that the value is the current value of `value.next`. Compare that with `front.next = front.next.next;` which modifies the object referred to by the current value of `front`. You might find this question useful: https://stackoverflow.com/questions/32010172/what-is-the-difference-between-a-variable-object-and-reference – Jon Skeet Mar 28 '19 at 20:10

1 Answers1

0

Java is pass-by-value. front = head copies the reference value from head into front. Because of that front = front.next has no effect on the head. In the loop front is created only to point into current element, it's not used to maintain the list.

However front.next = front.next.next changes the next field in an object referenced by front. There is no reference copy for next field here, like previously front was a copy of head.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111