链表:判断链表中是否有环

88 阅读1分钟

image.png 方法1: 声明两个快慢指针,一个走的快,一个走慢,如果有环,必定相遇


/**
 * @param head ListNode类 
 * @return bool布尔型
 */
function hasCycle( head ) {
    if(!head || !head.next) return false
    let fast = head;
    let slow = head;
    
    while(fast && fast.next) { // 判断快指针
        slow = slow.next;
        fast = fast.next.next;
        
        if(fast == slow) return true
    }
    return false
    
}
module.exports = {
    hasCycle : hasCycle
};

方法2 每次遍历的时候加个标记,如果下次遍历有这个标志,说明这个遍历过一次,说明有环。

function hasCycle( head ) {
    // write code here

    if (!head || !head.next) return false;
    
    while(head && head.next) {
        if (head.flag) return true;
       head.flag = true;
       head = head.next;
    }
    return false;
}