Linked List Cycle

LeetCode

LeetCode: https://leetcode.com/problems/linked-list-cycle/

Given head, determine if the linked list has a cycle in it.

Use fast and slow pointers (Floyd's cycle detection).

1def hasCycle(head: Optional[ListNode]) -> bool:
2 slow = head
3 fast = head
4
5 while fast and fast.next:
6 slow = slow.next
7 fast = fast.next.next
8 if slow == fast:
9 return True
10
11 return False
slow
fast
3
0
2
1
0
2
-4
3
cycleTo=1
Step 1 / 4
Step 1:
Initialize slow and fast at head. Tail points back to index 1.
Pointers: fast=0, slow=0
Focus: select @ [0]
cycleTo=1