美文网首页
160. Intersection of Two Linked

160. Intersection of Two Linked

作者: 7ccc099f4608 | 来源:发表于2020-03-18 13:52 被阅读0次

https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

image.png

(图片来源https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

日期 是否一次通过 comment
2020-03-18 0
2020-03-18 0

public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        //boundary check
        if(headA == null || headB == null) {
            return null;
        }

        ListNode a = headA, b = headB;

        /**
         *
         * 1. 如果A/B长度相同,则能够同时遍历到交点;
         * 2. 如果长度不同,则较短的链表先到终点null(假设为A),然后a赋值为较长的链表(假设为B)。
         *    于是等较长的链表B到达终点时(b上的),a已经走过了A/B链表的长度差(len(B)-len(A))。
         *    此时,把b赋值为A,二者同时从距离终点null等长的地方开始遍历,寻找交点。
         * 如果两链表没有交点,则会死循环遍历下去
         * */
        while( a != b) {
            //for the end of first iteration, we just reset the pointer to the head of another linkedlist
            a = a == null ? headB : a.next;
            b = b == null ? headA : b.next;
        }

        return a;
    }

相关文章

网友评论

      本文标题:160. Intersection of Two Linked

      本文链接:https://www.haomeiwen.com/subject/qfwqyhtx.html