Algo-Sim › Linked Lists
Linked List Cycle
Easy · Linked Lists · step through it in Java, Python and C++ on your own input
Detect a cycle with Floyd's fast and slow pointers, in O(1) extra space.
Problem
Given the head of a linked list, return true if following next pointers ever revisits a node (the list has a cycle), and false if it reaches null. The pos input only describes where the tail links back; the code never sees it.
Constraints
- 0 ≤ number of nodes ≤ 10⁴
- -10⁵ ≤ Node.val ≤ 10⁵
- pos is −1 or a valid index
- Follow-up: O(1) memory
Edge cases to test
- Empty list
- A self-loop on one node
- A cycle that starts at the head
Follow-up questions
- Why must fast meet slow?
- Inside the cycle the gap shrinks by one each step, so it reaches 0 within one lap.
- Where does the cycle begin?
- After they meet, move one pointer to the head and step both by one; they meet at the start (LC 142).
- What is the hash set alternative?
- Store visited nodes: O(n) time and O(n) space.
Solution
Java
public 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;
}Python
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return FalseC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)