[面试题 02.08]. 环路检测(39)

87 阅读1分钟

这道题写过,之前的连表中是否有环,并且环在第几个节点,快慢指针的影响比较深

方法一

简单,每一个都加入数组,如果发现数组中已经有 说明这个点位就是环形的入口

var detectCycle = function(head) {
    let arr = []
    
    while(head) {
        if(arr.includes(head)) {
            return head;
        }
        arr.push(head);
        head = head.next;
    }

    // console.log('no cycle')
    return null;
    
};

方法二

var detectCycle = function(head) {
    // 快慢指针判断环行连表
    let fast = head, slow = head;
    
    while(fast && fast.next) {
       
        fast = fast.next.next;
        slow = slow.next;
        // 快慢指针相遇了 说明有环, 再开始判断换的位置
      
         if(fast === slow){
            let start = head;
             while(start && slow) {
                 if(start === slow) {
                     return start;
                 }
                 start = start.next;
                 slow = slow.next;
                 
             }
         }
    }

    // console.log('no cycle')
    return null;
    
    
};

对应这个环形检测2的文章