Skip to content

Commit 21bc65a

Browse files
committed
committed from zkp
1 parent f4a1ddb commit 21bc65a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

LeetCode/detectCycle.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Definition for singly-linked list.
2+
# class ListNode(object):
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.next = None
6+
7+
class Solution(object):
8+
def detectCycle(self, head):
9+
"""
10+
:type head: ListNode
11+
:rtype: ListNode
12+
"""
13+
if head and head.next:
14+
slow = head
15+
fast = head.next
16+
else:
17+
return None
18+
while fast:
19+
# fast比slow多走了一圈
20+
# 在他们相遇的地点到环的最后一个节点之间的节点刚好等于从head到入环的第一个节点的前一个节点
21+
if fast == slow:
22+
slow_1 = head
23+
while True:
24+
if slow_1 == slow.next:
25+
return slow_1
26+
else:
27+
slow_1 = slow_1.next
28+
slow = slow.next
29+
30+
if fast.next:
31+
fast = fast.next.next
32+
slow = slow.next
33+
else:
34+
return None
35+
return None
36+

0 commit comments

Comments
 (0)