Skip to content

Linked List Cycle

LeetCode

01 · Question

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

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

02 · Solution

Reference solution

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