-
Notifications
You must be signed in to change notification settings - Fork 4
/
intersection_of_two_linked_lists.py
109 lines (77 loc) · 3.31 KB
/
intersection_of_two_linked_lists.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
99
100
101
102
103
104
105
106
107
108
109
"""
160. 相交链表
哈希表 链表 双指针
简单
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
图示两个链表在节点 c1 开始相交:
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构 。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Intersected at '8'
解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。
在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
示例 2:
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Intersected at '2'
解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。
在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
示例 3:
输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。
由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
这两个链表不相交,因此返回 null 。
提示:
listA 中节点数目为 m
listB 中节点数目为 n
0 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA <= m
0 <= skipB <= n
如果 listA 和 listB 没有交点,intersectVal 为 0
如果 listA 和 listB 有交点,intersectVal == listA[skipA + 1] == listB[skipB + 1]
进阶:你能否设计一个时间复杂度 O(n) 、仅用 O(1) 内存的解决方案?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists
"""
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
def __str__(self):
return '{}{}'.format(self.val, ',{}'.format(self.next) if self.next else '')
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not (headA and headB):
return None
pa = headA
pb = headB
while pa != pb:
pa = headB if pa is None else pa.next
pb = headA if pb is None else pb.next
return pa
if __name__ == '__main__':
solution = Solution()
inter_n = ListNode(8, next=ListNode(4, next=ListNode(5)))
n1 = ListNode(4, next=ListNode(1, next=inter_n))
n2 = ListNode(5, next=ListNode(0, next=ListNode(1, next=inter_n)))
result = solution.getIntersectionNode(n1, n2)
print(result)
assert str(result) == '8,4,5'
inter_n = ListNode(2, next=ListNode(4))
n1 = ListNode(0, next=ListNode(9, next=ListNode(1, next=inter_n)))
n2 = ListNode(3, next=inter_n)
result = solution.getIntersectionNode(n1, n2)
print(result)
assert str(result) == '2,4'
n1 = ListNode(2, next=ListNode(6, next=ListNode(4)))
n2 = ListNode(1, next=ListNode(5))
result = solution.getIntersectionNode(n1, n2)
print(result)
assert result is None