牛客网算法题JS(五)NC4 判断链表中是否有环

48 阅读1分钟

image.png

image.png


function ListNode(x){
this.val = x;
this.next = null;
}
  
/**
 *
 * @param head ListNode类
 * @return bool布尔型
 */
function hasCycle(head) {
    // write code here

    // 1.先判断链表head头部是否为空,链表是否为空链表
    if (head === null || head.next === null) return false;

    // 2.定义快慢指针
    let fast = head.next;
    let slow = head;

    // 3.如果fast.next为空,则fast为链表最后一个节点,无环
    while (fast && fast.next) {
        if (fast === slow) return true;  // 快慢指针在同一位置时,表示有环
        fast = fast.next.next;
        slow = slow.next;
    }
    return false;
}
module.exports = {
    hasCycle: hasCycle,
};