-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path142. Linked List Cycle II.py
58 lines (50 loc) · 1.25 KB
/
142. Linked List Cycle II.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
hash_set = set()
node = head
while node:
if node in hash_set:
return node
hash_set.add(node)
node = node.next
return None
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
meet = self.find(head)
if not meet:
return None
p1 = head
p2 = meet
while p1 != p2:
p1 = p1.next
p2 = p2.next
return p1
def find(self, head):
# 找到相遇点
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return fast
if not fast or not fast.next:
return None