File tree Expand file tree Collapse file tree 1 file changed +9
-5
lines changed
Python/chapter02/2.8 - Loop Detection Expand file tree Collapse file tree 1 file changed +9
-5
lines changed Original file line number Diff line number Diff line change @@ -171,16 +171,20 @@ def loop_detection_linear_time_const_space(ll: LinkedList):
171171 A linked list is 'circular' when a node's
172172 next pointer points to an earlier node, so
173173 as to make a loop in the linked list.
174+ Floyd cycle-finding algorithm:
175+ https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/
174176 Runtime: O(n)
175177 Space Complexity: O(1)
176178 :param ll: an input linked list
177179 :return: the corrupt node or None
178180 """
179- curr_node = ll .head
180- while curr_node is not None :
181- if curr_node is ll .tail .next :
182- return curr_node
183- curr_node = curr_node .next
181+ slow_ptr = ll .head
182+ fast_ptr = ll .head
183+ while slow_ptr and fast_ptr and fast_ptr .next :
184+ slow_ptr = slow_ptr .next
185+ fast_ptr = fast_ptr .next .next
186+ if slow_ptr is fast_ptr or slow_ptr is fast_ptr .next :
187+ return slow_ptr
184188 return None
185189
186190
You can’t perform that action at this time.
0 commit comments