Skip to content

Commit 26df293

Browse files
authored
Optimize has_loop using Floyd's cycle detection
Refactored has_loop method to use the Floyd's cycle-finding algorithm for detecting loops in a linked list.
1 parent 25c712f commit 26df293

1 file changed

Lines changed: 11 additions & 5 deletions

File tree

‎data_structures/linked_list/has_loop.py‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,17 @@ def has_loop(self) -> bool:
3737
>>> root_node.has_loop
3838
True
3939
"""
40-
try:
41-
list(self)
42-
return False
43-
except ContainsLoopError:
44-
return True
40+
slow = self
41+
fast = self
42+
43+
while fast is not None and fast.next_node is not None:
44+
slow = slow.next_node
45+
fast = fast.next_node.next_node
46+
47+
if slow is fast:
48+
return True
49+
50+
return False
4551

4652

4753
if __name__ == "__main__":

0 commit comments

Comments
 (0)