We have the following approach to merge two singly-linked list in java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//the next node of dummy will be pointing at the final result so it is easier to return
ListNode dummy = new ListNode(0);
ListNode result = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
result.next = l1;
l1 = l1.next;
} else {
result.next = l2;
l2 = l2.next;
}
result = result.next;
}
if (l1 != null) {
result.next = l1;
} else {
result.next = l2;
}
return dummy.next;
}
}
My question is after assigning dummy to result, dummy changes as result changes. This is intuitively correct because when I access the next of result, I am accessing the next of dummy.
However, for when I have an assignment like int a = 5;
and change reassign a = 6
, we would not get 5 == 6 apparently.
Or if I do result = ListNode(1)
, my guess is dummy would not be changed to ListNode(1).
What is the logic behind their distinctions?