implementing a singly-linked-list containing one integer and the reference to the next element. I wrote 2 methods which display the entire list.
VERSION A does contain the local variable current.
VERSION B does not contain a "current" variable. Both versions work fine, I however dont understand why VERSION B without a local variable works too.
public class LList{
// VERSION A
public static void printListA(Node Head){
Node current = Head;
while(current != null){
System.out.println(current._value);
current = current._next;
}
}
// VERSION B
public static void printListB(Node Head){
while(Head != null){
System.out.println(Head._value);
Head = Head._next;
}
}
Question to Version B: Since a Node-instance qualifies as a mutable object, it is passed by reference to the "printListB-function". I would therefore expect the Head-node to be changed by "printListB", since "Head" is over-written at each iteration ("Head" should become the Tail-node). This is however not the case, and it seems that "Head" is treated like a variable local to the function.
Could somebody explain, why printListB does not change the Parameter "Head" despite it being passed by reference.
Thanks a lot in advance.