160. Intersection of Two Linked Lists

// 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;
/*

  1. Use two pointers: (two list with different len)
  2. 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.
  3. 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.
  4. Try the process on paper, pA ,pB move forward with the same speed;
  5. 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;
  6. 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;
  7. 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;
            }          
        }       
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值