Linked List Cycle: the idea to remember.
Determine whether repeatedly following next pointers eventually enters a cycle.
The core insight
Move one pointer one step and another pointer two steps until they meet or the fast pointer reaches the end.
Why it works
Inside a cycle the relative offset changes by one each iteration, so it must eventually become zero. In an acyclic list the fast pointer reaches null.
The mistake to avoid
Compare node references, not their values, and check fast.next before advancing twice.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.