File tree Expand file tree Collapse file tree 1 file changed +18
-8
lines changed
Python/chapter02/2.8 - Loop Detection Expand file tree Collapse file tree 1 file changed +18
-8
lines changed Original file line number Diff line number Diff line change @@ -176,16 +176,26 @@ def loop_detection_const_space(ll: LinkedList) -> Optional[Node]:
176
176
:param ll: an input linked list
177
177
:return: the corrupt node or None
178
178
"""
179
+ # for the case of a single-node corrupt linked list
179
180
if ll .head and ll .head .next is ll .head :
180
181
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
189
199
return None
190
200
191
201
You can’t perform that action at this time.
0 commit comments