142. 环形链表 II
为保证权益,题目请参考 142. 环形链表 II(From LeetCode).
解决方案1
Python
python
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head is None:
return None
low = head
fast = head
while True:
fast = fast.next
if fast is None:
return None
fast = fast.next
if fast is None:
return None
low = low.next
if fast is low:
break
p1 = head
p2 = fast
while p1 is not p2:
p1 = p1.next
p2 = p2.next
return p1
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
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