Linked List Cycle (LeetCode 141)
thoughts
- 使用 Floyd’s Cycle Detection (快慢指針):
- slow 每次走一步,fast 每次走兩步
- 如果存在 cycle → fast 會追上 slow
Kotlin
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
class Solution {
fun hasCycle(head: ListNode?): Boolean {
var slow = head
var fast = head
while (fast?.next != null) {
slow = slow?.next
fast = fast.next?.next
if (slow == fast) return true
}
return false
}
}
Follow-up
- 如果要找 cycle 的入口點?(LeetCode 142)
- 如果只能修改節點結構,可以考慮標記 visited flag。
- 如果記憶體有限,能否不用快慢指針?(HashSet 但 O(n) 空間)