Skip to content

160. Intersection of Two Linked Lists

https://leetcode.com/problems/intersection-of-two-linked-lists/

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

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function(headA, headB) {
    let temp = headA
    let lenA = 0
    while (temp) {
        lenA += 1
        temp = temp.next
    }

    temp = headB
    let lenB = 0
    while (temp) {
        lenB += 1
        temp = temp.next
    }

    let longHead = lenA > lenB ? headA : headB
    let shortHead = lenA > lenB ? headB : headA
    for (let i = 0; i < Math.abs(lenA - lenB); i++) {
        longHead = longHead.next
    }

    while (longHead && longHead != shortHead) {
        longHead = longHead.next
        shortHead = shortHead.next
    }

    return longHead
};