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;
    
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容