-
Notifications
You must be signed in to change notification settings - Fork 1
/
link_list_cycle.py
98 lines (91 loc) · 2.47 KB
/
link_list_cycle.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# coding=utf-8
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
https://leetcode.com/problems/linked-list-cycle/solution/
提供了两种解决方法,hash 和两个快慢指针
"""
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
def hasCycle1(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
if not head.next:
return False
node_set = set()
current = head
while current:
if current not in node_set:
node_set.add(current)
current = current.next
else:
return True
return False
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not (head and head.next):
return
node_set = set()
current = head
while current:
if current not in node_set:
node_set.add(current)
current = current.next
else:
return current
return
def detectCycle1(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not (head and head.next):
return
fast = slow = head
# 找到快慢指针相遇的点
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if not fast or not fast.next:
return
meet_point = slow
fast = head
while fast != meet_point:
fast = fast.next
meet_point = meet_point.next
return meet_point
def detectCycle2(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return
fast = slow = head
# 找到快慢指针相遇的点
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
fast = head
while fast != slow:
fast = fast.next
slow = slow.next
return slow
return