链表交叉节点

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
const getIntersectionNode = (headA, headB) => {
    let weakMap = new WeakMap()
    while (headA) {
        if (!weakMap.has(headA)) {
            weakMap.set(headA, headA)
        }
        headA = headA.next
    }
    while (headB) {
        if (weakMap.has(headB)) {
            return weakMap.get(headB)
        }
        headB = headB.next
    }
    return null
};

  

posted @ 2020-10-25 00:11  671_MrSix  阅读(147)  评论(0编辑  收藏  举报