160. Intersection of Two Linked Lists 未看到时间结果

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.
这道题有很多种解法,如果不管Note,有很多解法是比较好想的,但是只有一种办法可以满足上面提出的所有条件。
使用双指针,分别从两个链表的头开始,指针到尾部了就定位到另一个链表的头部,如果链表是相交的,那么两个指针就会碰见,至于为啥,画个链表走走就知道了。如果两个链表不相交,那就会有一个指针有两次走到末尾。

var getIntersectionNode = function(headA, headB) {
    if (!headA||!headB)
        return;
    var pointer1 = headA;
    var pointer2 = headB;
    var flag = 0;
    while (pointer1!==pointer2) {
        if (!pointer1.next) {
            if(flag===2)
                return null;
            pointer1 = headB;
            flag++;
        }
        else
            pointer1 = pointer1.next;
        if (!pointer2.next) {
            if(flag===2)
                return null;
            pointer2 = headA;
            flag++;
        }
        else
            pointer2 = pointer2.next;
    }
    return pointer1;
    
};

你可能感兴趣的:(160. Intersection of Two Linked Lists 未看到时间结果)