LeetCode 141 Linked List Cycle - Implementation

The approach

Slow moves one step, fast moves two. If they meet, there's a cycle.

function hasCycle(head): if not head or not head.next: return false slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return true return false

O(n)O(n) time, O(1)O(1) space.