Skip to content

Commit 95433c3

Browse files
committed
update soln to avoid nested while loop
1 parent 6f28321 commit 95433c3

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

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

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -178,26 +178,31 @@ def loop_detection_linear_time_const_space(ll: LinkedList):
178178
:param ll: an input linked list
179179
:return: the corrupt node or None
180180
"""
181+
# for the case of a linked list with
182+
# a single node, non-corrupt
183+
if ll.head and ll.head.next is None:
184+
return None
181185
slow_ptr = ll.head
182186
fast_ptr = ll.head
183187
while slow_ptr and fast_ptr and fast_ptr.next:
184188
slow_ptr = slow_ptr.next
185189
fast_ptr = fast_ptr.next.next
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
200-
return None
190+
if fast_ptr.next is None:
191+
return None
192+
if slow_ptr is fast_ptr:
193+
# we have a cycle
194+
break
195+
# if we get here, then there is a cycle.
196+
# advance one of fast or slow pointers
197+
# and a pointer that starts in the
198+
# beginning, by one until they match.
199+
# they will end at the beginning of
200+
# the cycle.
201+
p = ll.head
202+
while p is not slow_ptr:
203+
p = p.next
204+
slow_ptr = slow_ptr.next
205+
return p
201206

202207

203208
def loop_detection_const_space(ll: LinkedList) -> Optional[Node]:

0 commit comments

Comments
 (0)