-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path07_linked_list_cycle_2.py
More file actions
76 lines (60 loc) · 1.65 KB
/
07_linked_list_cycle_2.py
File metadata and controls
76 lines (60 loc) · 1.65 KB
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
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def build_linked_list(arr, pos=-1):
"""
Builds a linked list from array arr.
If pos >= 0, creates a cycle by connecting the tail to the node at index pos.
"""
if not arr:
return None
head = ListNode(arr[0])
current = head
nodes = [head]
for val in arr[1:]:
node = ListNode(val)
current.next = node
current = node
nodes.append(node)
if pos != -1:
current.next = nodes[pos]
return head
class Solution:
def detectCycle_1(self, head: 'ListNode') -> 'ListNode':
visited = set()
cur = head
while cur:
if cur in visited:
return cur
visited.add(cur)
cur = cur.next
return None
def detectCycle(self, head: 'ListNode') -> 'ListNode':
if not head or not head.next:
return None
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if not fast or not fast.next:
return None
p = head
while p != slow:
slow = slow.next
p = p.next
return slow
if __name__ == "__main__":
head1 = build_linked_list([3,2,0,-4], pos=1)
head2 = build_linked_list([1,2], pos=0)
head3 = build_linked_list([1], pos=-1)
sol = Solution()
sol1 = sol.detectCycle(head1)
print(sol1.val)
sol2 = sol.detectCycle(head2)
print(sol2.val)
sol3 = sol.detectCycle(head3)
print(sol3)