两个链表的第一个公共节点(相交链表)

一、思路

集合法,先遍历第一个链表,将节点放入集合,然后遍历第二个链表判断其节点是否在集合中.

二、程序实现

var getIntersectionNode = function(headA, headB) {
    const set=new Set();
    let tempA=headA;
    while(tempA){
        set.add(tempA);
        tempA=tempA.next;
    }
    let tempB=headB;
    while(tempB){
        if(set.has(tempB)){
            return tempB;
        }
        tempB=tempB.next;
    }
    return null
};
posted @ 2022-05-09 20:19  花村店长  阅读(46)  评论(0)    收藏  举报