Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Linked List Cycle in Python
A linked list cycle occurs when a node in the linked list points back to a previous node, creating a loop. To detect cycles, we can use a hash set to track visited nodes or implement Floyd's cycle detection algorithm (tortoise and hare).
The cycle is represented by a pos parameter indicating where the tail connects. If pos = -1, no cycle exists. For example, in the list [5, 3, 2, 0, -4, 7] with pos = 1, the tail connects to the second node (index 1), creating a cycle.
Using Hash Set Approach
This method tracks visited nodes using a set. If we encounter a node already in the set, a cycle exists ?
class ListNode:
def __init__(self, data, next=None):
self.data = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
current = head
for element in elements[1:]:
current.next = ListNode(element)
current = current.next
return head
def get_node(head, pos):
if pos == -1:
return None
current = head
for _ in range(pos):
current = current.next
return current
class Solution:
def hasCycle(self, head):
visited = set()
current = head
while current:
if current in visited:
return True
visited.add(current)
current = current.next
return False
# Create linked list [5, 3, 2, 0, -4, 7]
head = make_list([5, 3, 2, 0, -4, 7])
# Create cycle: tail connects to node at position 1
last_node = head
while last_node.next:
last_node = last_node.next
pos = 1
cycle_node = get_node(head, pos)
last_node.next = cycle_node
# Check for cycle
solution = Solution()
print(solution.hasCycle(head))
True
Using Floyd's Cycle Detection (Two Pointers)
This space-efficient approach uses two pointers moving at different speeds. If they meet, a cycle exists ?
class Solution:
def hasCycle(self, head):
if not head or not head.next:
return False
slow = head # Moves one step
fast = head # Moves two steps
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
# Test with the same linked list
head = make_list([5, 3, 2, 0, -4, 7])
# Create cycle
last_node = head
while last_node.next:
last_node = last_node.next
pos = 1
cycle_node = get_node(head, pos)
last_node.next = cycle_node
# Check for cycle
solution = Solution()
print(solution.hasCycle(head))
True
Comparison
| Method | Time Complexity | Space Complexity | Advantage |
|---|---|---|---|
| Hash Set | O(n) | O(n) | Simple to implement |
| Two Pointers | O(n) | O(1) | Constant space usage |
Conclusion
Both approaches effectively detect linked list cycles with O(n) time complexity. Use the hash set method for simplicity, or Floyd's algorithm for optimal space efficiency with O(1) memory usage.
