Write a program that detects a cycle in a linked list.
- User
Write a program that detects a cycle in a linked list.
Assistant
Write a program that detects a cycle in a linked list.
The user wants a program to detect a cycle in a linked list. I need to provide code for this. What language? Python is a good default choice for algorithms, but C++ or Java are also common. I'll provide a Python implementation because it's concise and easy to read, but I might add C++ if I feel generous. Let's stick to Python as the primary example.
The standard algorithm for cycle detection is Floyd's Cycle-Finding Algorithm, often called the "tortoise and the hare" algorithm. How does it work?
slow and fast, both pointing to the head of the list.slow one step at a time (slow = slow.next).fast two steps at a time (fast = fast.next.next).fast reaches the end (None or null). This means there is no cycle.fast meets slow (i.e., fast == slow). This means there is a cycle.I should also mention the HashSet approach. How does it work?
visited.visited.
visited and move to next.None is reached, no cycle.Comparison:
Floyd's is generally preferred because of the O(1) space complexity.
Plan:
ListNode class.has_cycle(head).Let's draft the Python code.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def has_cycle(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
Let's refine the test case. Create nodes: 1 -> 2 -> 3 -> 4. Case 1: 4 points to None (No cycle). Case 2: 4 points to 2 (Cycle).
I will present Floyd's algorithm as the primary solution because it's the standard "optimal" interview answer. I will explain the logic clearly.
Structure of the response:
Let's stick to the Python implementation as the main answer.
Check edge cases in the code:
if not head handles it.if not head.next handles it (actually, the loop condition while fast and fast.next handles most of this, but initializing pointers needs care).
fast and fast.next fails immediately, returns False. Correct.Let's write the final output. Here is a standard implementation of Floyd's Cycle-Finding Algorithm, also known as the "Tortoise and the Hare" algorithm.
This approach is preferred because it is efficient, requiring O(n) time complexity and O(1) (constant) space complexity.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def has_cycle(head: ListNode) -> bool:
"""
Detects if a linked list has a cycle using
Floyd's Cycle-Finding Algorithm.
"""
# If the list is empty or has only one node, no cycle is possible
if not head or not head.next:
return False
# Initialize two pointers
slow = head
fast = head
# Traverse the list
while fast and fast.next:
slow = slow.next # Move slow pointer by 1 step
fast = fast.next.next # Move fast pointer by 2 steps
# If the pointers meet, there is a cycle
if slow == fast:
return True
# If fast reaches the end (None), there is no cycle
return False
# --- Example Usage ---
# Helper to create a list without a cycle
def create_linear_list(length):
nodes = [ListNode(i) for i in range(length)]
for i in range(length - 1):
nodes[i].next = nodes[i+1]
return nodes[0]
# Helper to create a list with a cycle
def create_cyclic_list(length, cycle_start_index):
nodes = [ListNode(i) for i in range(length)]
for i in range(length - 1):
nodes[i].next = nodes[i+1]
# Create the cycle: point the last node back to the start index
nodes[length-1].next = nodes[cycle_start_index]
return nodes[0]
# Test Case 1: No Cycle
head_no_cycle = create_linear_list(5)
print(f"List with no cycle: {has_cycle(head_no_cycle)}") # Output: False
# Test Case 2: Has Cycle
head_with_cycle = create_cyclic_list(5, 2) # 0->1->2->3->4 -> (back to 2) ...
print(f"List with cycle: {has_cycle(head_with_cycle)}") # Output: True
slow and fast, both starting at the head of the list.slow pointer moves one step at a time.fast pointer moves two steps at a time.fast pointer will eventually reach the end of the list (None), and the function returns False.fast pointer will eventually enter the loop and "lap" the slow pointer. Since fast moves faster, it will catch up to slow inside the loop. When slow == fast, the function returns True.slow and fast) for tracking, regardless of the size of the linked list.