链表中环的入口节点

对于一个给定的链表,返回环的入口节点,如果没有环,返回null
拓展:
你能给出不利用额外空间的解法么?

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
 * 
 * @param head ListNode类 
 * @return ListNode类
 */
function detectCycle( head ) {
    // write code here
    if(head==null||head.next==null){return null}
    var slow = head
    var fast = head
    while(fast&&fast.next){
        slow = slow.next
        fast = fast.next.next
        if(fast==slow){
           let p = head
           while(p!==slow){
               p = p.next
               slow = slow.next
           }
            return p
        }
    }
    return null
}
module.exports = {
    detectCycle : detectCycle
};
链表算法 文章被收录于专栏

链表相关算法

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 14:00
不想多说了,什么逆天HR,还要教我礼貌😂
机械打工仔:这不纯傻卵吗,他还操心上别人老板了
投递BOSS直聘等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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