Skip to content

📚 6.链表相交

💻 代码实现

typescript
/**
 * @url https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
 */
function ListNode(val) {
    this.val = val
    this.next = null
}

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */

const getLens = (head) => {
    let count = 0,
        curNode = head
    while (curNode) {
        count++
        curNode = curNode.next
    }
    return count
}

var getIntersectionNode = function (headA, headB) {
    let len1 = getLens(headA),
        len2 = getLens(headB),
        curNodeA = headA,
        curNodeB = headB,
        chazhi = Math.abs(len1 - len2),
        count = 0
    if (len1 > len2) {
        while (count < chazhi) {
            curNodeA = curNodeA.next
            count++
        }
    } else {
        while (count < chazhi) {
            curNodeB = curNodeB.next
            count++
        }
    }

    while (curNodeA) {
        if (curNodeA === curNodeB) return curNodeA
        curNodeA = curNodeA.next
        curNodeB = curNodeB.next
    }
    return null
}

Released under the MIT License.