[leetCode]面试题 02.07. 链表相交

![在这里插入图片描述]( https://img-blog.csdnimg.cn/20201023211701401.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JlbndlaXlpMTQ4Nw==,size_16,color_FFFFFF,t_70#pic_center)

双指针

通过交换指针位置来使指针在循环过程中达到相同的位置

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pA = headA;
        ListNode pB = headB;
        while (true) {
            if (pA == null && pB == null) return null;
            if (pA == null) {
                pA = headB;
            }
            if (pB == null) {
                pB = headA;
            }
            if (pA == pB) return pB;
            pA = pA.next;
            pB = pB.next;
        }
    }
}
posted @ 2020-10-23 21:45  消灭猕猴桃  阅读(80)  评论(0)    收藏  举报