We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent f4a1ddb commit 21bc65aCopy full SHA for 21bc65a
LeetCode/detectCycle.py
@@ -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
27
+ slow_1 = slow_1.next
28
+ slow = slow.next
29
30
+ if fast.next:
31
+ fast = fast.next.next
32
33
34
35
36
0 commit comments