Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions data_structures/linked_list/has_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,28 @@ def has_loop(self) -> bool:
>>> root_node.next_node.next_node.next_node = root_node.next_node
>>> root_node.has_loop
True
>>> single_node = Node(1)
>>> single_node.next_node = single_node
>>> single_node.has_loop
True
>>> loop_to_root = Node(1)
>>> loop_to_root.next_node = Node(2)
>>> loop_to_root.next_node.next_node = loop_to_root
>>> loop_to_root.has_loop
True
>>> dup_node = Node(5)
>>> dup_node.next_node = Node(5)
>>> dup_node.has_loop
False
"""
try:
list(self)
return False
except ContainsLoopError:
return True
slow: Node | None = self
fast: Node | None = self
while fast and fast.next_node and slow:
slow = slow.next_node
fast = fast.next_node.next_node
if slow is fast:
return True
return False


if __name__ == "__main__":
Expand All @@ -61,3 +77,6 @@ def has_loop(self) -> bool:

root_node = Node(1)
print(root_node.has_loop) # False

root_node.next_node = root_node
print(root_node.has_loop) # True
Loading