Write a program to find the node at which the intersection of two singly linked lists begins.


For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.


Notes:

  • If the two linked lists have no intersection at all, return null.

  • The linked lists must retain their original structure after the function returns.

  • You may assume there are no cycles anywhere in the entire linked structure.

  • Your code should preferably run in O(n) time and use only O(1) memory.

问题分析,看到该问题,直接想到使用hash函数来处理两个链表,则时间复杂度o(n)空间复杂度o(n)。

然而题目要求,时间复杂度o(n)空间复杂度o(1),因此不能使用hash来处理该问题。我们想两个链表有交集,即后半部分是重合的,两条链表有长有短,重合部分一定存在于最短的链表内。因此,以最短的链表长度,裁剪掉长链表前边的部分,然后和短链表,依次比对链表中的节点,看是否有重合。


public class Solution {

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        int La=0;

        int Lb=0;

        ListNode a=headA;

        while(a!=null)

        {

            La++;

            a=a.next;

        }

        ListNode b=headB;

        while(b!=null)

        {

            Lb++;

            b=b.next;

        }

        if(La==Lb)

        {

            a=headA;

            b=headB;

            while(a!=null)

            {

                if(a==b)

                    return a;

                a=a.next;

                b=b.next;

            }

        }

        else if(La>Lb)

        {

            a=headA;

            b=headB;

            int i=0;

            while(i<La-Lb)

            {

                i++;

                a=a.next;

            }

        }

        else

        {

            a=headA;

            b=headB;

            int i=0;

            while(i<Lb-La)

            {

                i++;

                b=b.next;

            }

        }

        

        while(a!=null)

        {

            if(a==b)

                return a;

            a=a.next;

            b=b.next;

        }

        return null;

            

    }

}