面试题 02.07. 链表相交 JavaScript实现

69 阅读1分钟

面试题 02.07. 链表相交

题目链接

1、哈希表

var getIntersectionNode = function(headA, headB) {
    // 用一个哈希表存储headA中的元素
    let s = new Set();

    // 遍历headA中的节点,存储哈希表中,注意存储的是节点不是值,要不然会造成误会
    let temp = headA
    while(temp){
        s.add(temp)
        temp = temp.next
    }

    // 遍历headB,检查是否哈希表中有相同的元素(哈希表的作用)
    temp = headB
    while(temp){
        if(s.has(temp)){
            return temp
        }
        temp = temp.next
    }
    return null
};

在这里插入图片描述

2、双指针

详细解答 图解

var getIntersectionNode = function(headA, headB) {
    let A = headA, B = headB;

    while(A != B){
        // headA和headB都要遍历两遍,当headA遍历完,即遇空,就开始遍历headB
        // 遍历完两边之后,一定会在相交处相遇
        A = A == null ? headB : A.next
        B = B == null ? headA : B.next
    }
    return A
};

在这里插入图片描述