-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0160-intersection-of-two-linked-lists.py
More file actions
42 lines (30 loc) · 941 Bytes
/
0160-intersection-of-two-linked-lists.py
File metadata and controls
42 lines (30 loc) · 941 Bytes
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
# time complexity: O(n+m)
# space complexity: O(m)
from typing import Optional
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA: Optional[ListNode], headB: Optional[ListNode]) -> ListNode:
nodesBSet = set()
while headB:
nodesBSet.add(headB)
headB = headB.next
while headA:
if headA in nodesBSet:
return headA
headA = headA.next
return None
headA = ListNode(4)
headA.next = ListNode(1)
headA.next.next = ListNode(8)
headA.next.next.next = ListNode(4)
headA.next.next.next.next = ListNode(5)
headB = ListNode(5)
headB.next = ListNode(6)
headB.next.next = ListNode(1)
headB.next.next.next = ListNode(8)
headB.next.next.next.next = ListNode(4)
headB.next.next.next.next.next = ListNode(5)
print(Solution().getIntersectionNode(headA, headB))