Given the head of a linked list, determine if the linked list has a cycle in it.
A cycle exists if there is a node in the list that can be reached again by continuously following the next pointer.
Return true if there is a cycle in the linked list. Otherwise, return false.
The optimal solution uses two pointers moving at different speeds to detect a cycle.
Initialize Two Pointers:
slow pointer moves one step at a timefast pointer moves two steps at a timeTraverse the List:
slow forward by 1 nodefast forward by 2 nodesReturn Result:
fast reaches the end (null), there's no cycleslow and fast meet, there's a cycleNo Cycle: If there's no cycle, fast will eventually reach the end of the list.
With Cycle: If there's a cycle:
fast will catch up to slowfast reaches end in n/2 stepsfast catches slow within n stepsFor a list with cycle: 3 → 2 → 0 → -4 → (back to 2)
1/**
2 * Linked List Cycle - Floyd's Cycle Detection Algorithm
3 *
4 * Time Complexity: O(n)
5 * Space Complexity: O(1)
6 */
7
8class ListNode {
9 int val;
10 ListNode next;
11 ListNode(int x) {
12 val = x;
13 next = null;
14 }
15}
16
17public class Solution {
18 public boolean hasCycle(ListNode head) {
19 // Edge case: empty list or single node
20 if (head == null || head.next == null) {
21 return false;
22 }
23
24 // Initialize two pointers
25 ListNode slow = head;
26 ListNode fast = head;
27
28 // Traverse the list
29 while (fast != null && fast.next != null) {
30 // Move slow by 1 step
31 slow = slow.next;
32 // Move fast by 2 steps
33 fast = fast.next.next;
34
35 // If they meet, there's a cycle
36 if (slow == fast) {
37 return true;
38 }
39 }
40
41 // Fast reached the end, no cycle
42 return false;
43 }
44}
45
46// Alternative: Hash Set Approach
47class Solution2 {
48 public boolean hasCycle(ListNode head) {
49 Set<ListNode> visited = new HashSet<>();
50 ListNode current = head;
51
52 while (current != null) {
53 // If we've seen this node before, there's a cycle
54 if (visited.contains(current)) {
55 return true;
56 }
57
58 // Mark node as visited
59 visited.add(current);
60 current = current.next;
61 }
62
63 // Reached end, no cycle
64 return false;
65 }
66}
67