-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm142 v1 O(1) space.py
39 lines (32 loc) · 1 KB
/
m142 v1 O(1) space.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head :
return None
currFast = head
currSlow = head
loop: bool = False
while currFast.next and currFast.next.next :
currFast = currFast.next.next
currSlow = currSlow.next
if currFast == currSlow :
loop = True
break
if not loop :
return None
loopSize = 1
currFast = currFast.next
while currFast != currSlow :
loopSize += 1
currFast = currFast.next
currRef = head
while True :
for i in range(loopSize) :
currFast = currFast.next
if currFast == currRef :
return currRef
currRef = currRef.next