查找链表交叉点

178 阅读1分钟
const crossing = { name: "交叉点", next: { name: '继续1', next: { name: '继续2', next: null } } }

const linkList1 = { name: 1, next: { name: 2, next: { name: 3, next: { name: 3, next: crossing } } } }

const linkList2 = { name: 'a', next: { name: 'c', next: { name: 'd', next: crossing } } }

// 统计链表的长度
function countLinkListLength(linkList) {
    let len = 0
    while (linkList?.name) {
        len++
        linkList = linkList.next
    }
    return len
}

// 查找链接中交叉点
function searchCrossing(linkList1, linkList2) {
    const len1 = countLinkListLength(linkList1)
    const len2 = countLinkListLength(linkList2)
    // 不存在交叉点
    if (len1 === 0 || len2 === 0) {
        return
    }
    if (len1 > len2) {
        [linkList1, linkList2] = [linkList2, linkList1]
    }
    const map = new Map()
    do {
        map.set(linkList1, linkList1)
        linkList1 = linkList1.next
    } while (linkList1)
    do {
        if (map.has(linkList2)) {
            return linkList2
        }
        linkList2 = linkList2.next
    } while (linkList2)
}


console.log(searchCrossing(linkList1, linkList2))