I have written this code to return the intersection of two linked-lists. Still, at first I was comparing if(pointer1.val == pointer2.val)
and got an error, then I figured out that it should be if(pointer1==pointer2)
, I'm still a beginner and I can't recognize why I don't compare the values of the pointers, and what is the difference of pointer1==pointer2
and comparing their values...
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null || headB==null){
return null;
}
ListNode pointer1=headA;
ListNode pointer2=headB;
while(pointer1 !=pointer2){
pointer1=pointer1.next;
pointer2=pointer2.next;
if(pointer1==pointer2)
return pointer1;
if(pointer1==null){
pointer1=headB;
}
if(pointer2==null){
pointer2=headA;
}
}
return pointer1;
}
}
CodePudding user response:
why I don't compare the values of the pointers, and what is the difference of pointer1==pointer2 and comparing their values
Imagine a case where all the nodes have the same values:
headA -> [1] -> [1] -> [1] -> [1] -> [1] -> null
/
/
headB -> [1] -> [1]
If you would compare values, you'd find an equality the very first time -- when comparing the nodes that headA
and headB
point to. Although these have the same value, they are not the same nodes.
The goal of the algorithm is to find the first node that is shared by both lists (not just a shared value, but the node itself). So when we traverse with two pointers along the two lists we hope to find a state where both pointers reference the same node. This is equivalent to saying that these pointers have the same value.