题解 | #链表中环的入口结点#

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function EntryNodeOfLoop(pHead)
{
    if(pHead.next === null || pHead.next.next === null) {
        return null
    }
    
    // write code here
    let p1 = pHead
    let p2 = pHead
    let p3 = pHead
    let p4 = pHead
    let getSize = true
    let size = 0
    //获取环的长度
    while (getSize) {
        p1 = p1.next
        if(p2.next.next === null) {
            return null
        }
        p2 = p2.next.next
        if(p1 === p2) {
            const tem = p1
            while (getSize) {
                p1 = p1.next
                size ++
                if (p1 === tem) {
                    getSize = false
                }
            }
        }
        
    }
    console.log(1)
    if (getSize) {
        return null
    }
    let sum = 0
    let length = 0
    while (p3) {
        if(p3.flag) {
            length = sum-size
            break
        }
        sum++
        p3.flag = true
        p3 = p3.next
    }
    while (p4) {
        if(!length) {
            return p4
        }
        length--
        p4 = p4.next
    }
}
module.exports = {
    EntryNodeOfLoop : EntryNodeOfLoop
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务