Skip to content

Commit 6f28321

Browse files
committed
update soln
1 parent ddc3305 commit 6f28321

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

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

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,20 @@ def loop_detection_linear_time_const_space(ll: LinkedList):
183183
while slow_ptr and fast_ptr and fast_ptr.next:
184184
slow_ptr = slow_ptr.next
185185
fast_ptr = fast_ptr.next.next
186-
if slow_ptr is fast_ptr or slow_ptr is fast_ptr.next:
187-
return slow_ptr
186+
if slow_ptr is not fast_ptr:
187+
continue
188+
# if we get here, then there is a cycle.
189+
# advance one of fast or slow pointers
190+
# and a pointer that starts in the
191+
# beginning, by one until they match.
192+
# they will end at the beginning of
193+
# the cycle.
194+
p = ll.head
195+
while p and slow_ptr:
196+
if p is slow_ptr:
197+
return p
198+
p = p.next
199+
slow_ptr = slow_ptr.next
188200
return None
189201

190202

@@ -274,6 +286,16 @@ def setUp(self):
274286
LinkedList(1, 2, 3, 4, 5),
275287
LinkedList(7, 8, 9),
276288
Node(6)
289+
),
290+
CorruptLLStructure(
291+
LinkedList(),
292+
LinkedList(2, 3, 4, 5, 6, 7, 8, 9),
293+
Node(1)
294+
),
295+
CorruptLLStructure(
296+
LinkedList(1),
297+
LinkedList(3, 4, 5, 6, 7, 8, 9),
298+
Node(2)
277299
)
278300
]
279301
self.loop_detection_test_cases = []

0 commit comments

Comments
 (0)