// idea: a+allcommon+b = b + allcommon+a;
//a represents the len before the intersect pos in list A;
//b represents the len before the intersect pos in list B;
//take the lists as a whole, so the total len is same; they will meet at the intersection. for a+allcommon+b = b + allcommon+a;
/*
- Use two pointers: (two list with different len)
- First round,pA traverse list A first, if it reach the end of List A, then second round,let pA repoint to head of B, traverse List B.
- First round,pB traverse list B first, if it reach the end of List B, then second round let pB repoint to head of A, traverse List A.
- Try the process on paper, pA ,pB move forward with the same speed;
- you will find, two pointers will go the same distance in the end. the journey of pA :a +common+b; the journey of pB :b +common+a; common is same. So a+b = b+a;
- If two list have the intersection, they will meet at the intersection point(meet at first round, if they have same length; meet at the second round, if they have different length ). if(p1 == p2) return p1;
- If they not, they will point to null at the time, return null. if(p1 == null && p2 ==null) return null;
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB ==null) return null;
ListNode p1 = headA;
ListNode p2 = headB;
while(true){
if(p1 == p2) return p1; //if meet return p1 or p2
p1 = p1.next;//move forward
p2 = p2.next;
if(p1 == null && p2 ==null) return null;//two round,if they reach the end of their list at the same time, no intersection. return null.
if(p1 ==null){//if p1reach to its end,
p1 = headB;//let it point to the head of B
}
if(p2 == null){//similar as above
p2 = headA;
}
}
}
}