编辑代码

function ListNode(val) {
    this.val = val;
    this.next = null;
}
// 快速生成一个链表/链表环
function ListCyclet(arr, isCyclet = true) {
    if (!arr.length) return {}

    let head = new ListNode()
    let cur = head
    while (arr.length) {
        cur.next = new ListNode(arr.shift())
        cur = cur.next
    }
    isCyclet && (cur.next = head.next)
    return head.next
}

// 设置flag
function detectCycle(head) {
    while (head) {
        if (head.flag) {
            return head
        } else {
            head.flag = true
            head = head.next
        }
    }
    return null
}

// 快慢指针
function detectCycle2(head) {
    let slow = head
    let fast = head.next
    while (fast && fast.next) {
        if (fast === slow) {
            return true
        }
        slow = slow.next
        fast = fast.next.next
    }
    return null
}

let line = new ListNode(3)
line.next = new ListCyclet([2, 0, 4])

// console.log(detectCycle(line))
console.log(detectCycle2(line))
console.log(detectCycle2(new ListCyclet([1, 2, 3, 4, 5],false)))