Skip to main content

141. Linked List Cycle

分析

注意区分开始点的合理性

题解

✅正确的做法

function hasCycle(head: ListNode | null): boolean {
let slow = head, fast = head

while (slow && fast) {
slow = slow.next
fast = fast.next?.next

if (slow === fast) {
return true
}
}

return false
};

❌错误的

function hasCycle(head: ListNode | null): boolean {
let slow = head, fast = head?.next

while (slow && fast) {
slow = slow.next
fast = fast.next?.next

if (slow === fast) {
return true
}
}

return false
};