Skip to content

Commit cba9300

Browse files
committed
update comments and var names
1 parent e84c5e0 commit cba9300

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

Python/chapter02/2.8 - Loop Detection/miguel_soln_2.8.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -176,16 +176,26 @@ def loop_detection_const_space(ll: LinkedList) -> Optional[Node]:
176176
:param ll: an input linked list
177177
:return: the corrupt node or None
178178
"""
179+
# for the case of a single-node corrupt linked list
179180
if ll.head and ll.head.next is ll.head:
180181
return ll.head
181-
n1 = ll.head
182-
while n1 is not None:
183-
n2 = ll.head
184-
while n2 is not n1:
185-
if n1.next is n2:
186-
return n2
187-
n2 = n2.next
188-
n1 = n1.next
182+
# this algorithm will traverse through the
183+
# linked list, and at each element, we will loop from
184+
# the start up to the current node, comparing
185+
# the next pointer of the current node with
186+
# each node leading up to the current node
187+
curr_node = ll.head
188+
while curr_node is not None:
189+
n = ll.head # n is a node
190+
# we will be traversing 'n' up to the current node
191+
# to see if a previous node happens to be the
192+
# 'next' of the current node.
193+
while n is not curr_node:
194+
if curr_node.next is n:
195+
# cycle found
196+
return n
197+
n = n.next
198+
curr_node = curr_node.next
189199
return None
190200

191201

0 commit comments

Comments
 (0)