@@ -178,26 +178,31 @@ def loop_detection_linear_time_const_space(ll: LinkedList):
178
178
:param ll: an input linked list
179
179
:return: the corrupt node or None
180
180
"""
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
181
185
slow_ptr = ll .head
182
186
fast_ptr = ll .head
183
187
while slow_ptr and fast_ptr and fast_ptr .next :
184
188
slow_ptr = slow_ptr .next
185
189
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
201
206
202
207
203
208
def loop_detection_const_space (ll : LinkedList ) -> Optional [Node ]:
0 commit comments