diff --git a/data_structures/linked_list/has_loop.py b/data_structures/linked_list/has_loop.py index a25204e3c4ce..06d193e2d259 100644 --- a/data_structures/linked_list/has_loop.py +++ b/data_structures/linked_list/has_loop.py @@ -37,11 +37,14 @@ def has_loop(self) -> bool: >>> root_node.has_loop True """ - try: - list(self) - return False - except ContainsLoopError: - return True + slow_node = self + fast_node = self + while fast_node and fast_node.next_node: + slow_node = slow_node.next_node + fast_node = fast_node.next_node.next_node + if slow_node is fast_node: + return True + return False if __name__ == "__main__":