MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / Node

Class Node

data_structures/linked_list/has_loop.py:10–43  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8
9
10class Node:
11 def __init__(self, data: Any) -> None:
12 self.data: Any = data
13 self.next_node: Node | None = None
14
15 def __iter__(self):
16 node = self
17 visited = set()
18 while node:
19 if node in visited:
20 raise ContainsLoopError
21 visited.add(node)
22 yield node.data
23 node = node.next_node
24
25 @property
26 def has_loop(self) -> bool:
27 """
28 A loop is when the exact same Node appears more than once in a linked list.
29 >>> root_node = Node(1)
30 >>> root_node.next_node = Node(2)
31 >>> root_node.next_node.next_node = Node(3)
32 >>> root_node.next_node.next_node.next_node = Node(4)
33 >>> root_node.has_loop
34 False
35 >>> root_node.next_node.next_node.next_node = root_node.next_node
36 >>> root_node.has_loop
37 True
38 """
39 try:
40 list(self)
41 return False
42 except ContainsLoopError:
43 return True
44
45
46if __name__ == "__main__":

Callers 1

has_loop.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected