I have a class:
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
And the function to print the LinkedList is :
public static void printLinkedNode(ListNode l){
while(l != null){
System.out.print(l.val+" ");
l = l.next;
}
System.out.println(" ");
}
In my main function, I create a ListNode called test:
ListNode test = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
If I do A:
ListNode fast = head, slow = head;
fast = fast.next.next;
printLinkedNode(head); // I get 1->2->3->4
If I do B:
ListNode fast = head, slow = head;
fast.next = fast.next.next;
printLinkedNode(head); // I get 1->3->4
I am confused at why in A, the head is 1->2->3->4, but not 3->4? I have read some posts about Is Java “pass-by-reference” or “pass-by-value”?, but still can't figure it out..
If I do C:
ListNode fast = head, slow = head;
fast = fast.next.next;
printLinkedNode(fast); //3->4
printLinkedNode(head); //1->2->3->4
fast.next = new ListNode(5);
printLinkedNode(fast); //3->5
printLinkedNode(head); //1->2->3->5, why the head will change?
I am confused at why the head will change when we do fast.next = new ListNode(5); I think fast is not assign with head?