'use strict'

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

function ListNode(val) {
    this.val = val
    this.next = null
}

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function (headA, headB) {
    let set = new Set()
    let pA = headA,
        pB = headB
    while (pA !== null && pB != null) {
        if (set.has(pA)) return pA
        set.add(pA)
        if (set.has(pB)) return pB
        set.add(pB)
        pA = pA.next
        pB = pB.next
    }
    if (pA === pB) return null
    let curr = null
    if (pA === null) {
        curr = pB
    } else {
        curr = pA
    }
    while (curr !== null) {
        if (set.has(curr)) return curr
        set.add(curr)
        curr = curr.next
    }
    return null
}

function __main__() {
    let n2 = new ListNode(2)
    let n22 = new ListNode(3)
    let n23 = new ListNode(3)
    let n24 = new ListNode(3)
    n2.next = n22
    n22.next = n23
    n23.next = n24
    let n1 = new ListNode(3)
    let n12 = new ListNode(3)
    let n13 = new ListNode(3)
    n1.next = n12
    n12.next = n13
    n24.next = n12
    let n3 = new ListNode(3)
    /*eslint no-console: ["error", { allow: ["log"] }] */
    console.log(getIntersectionNode(n1, n2))
    console.log(getIntersectionNode(n2, n3))
}

__main__()