链接:160. 相交链表 - 力扣(LeetCode)

方法一:哈希 

把A链表都存入一个哈希表,B链表遍历通过哈希表定位有没有相同的Node,因为哈希表的插入查询都是O(1)。所以这里的时间复杂度就是O(m+n)

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def getIntersectionNode(self, headA, headB):
 9         """
10         :type head1, head1: ListNode
11         :rtype: ListNode
12         """
13         help_dict = {}
14         res = None
15         while headA:
16             help_dict[headA] = 1
17             headA = headA.next
18         while headB:
19             if headB in help_dict:
20                 res = headB
21                 return res
22             headB = headB.next
23         return res

 方法二:双指针

指针1过一遍A和B,指针2过一遍B和A,必定同时到达相交点或同时为空。证明过程详见下方官方题解

image

 

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def getIntersectionNode(self, headA, headB):
 9         """
10         :type head1, head1: ListNode
11         :rtype: ListNode
12         """
13         pA = headA
14         pB = headB
15         if pA == None or pB == None:
16             return None
17         while pA != pB:
18             if pA.next == None and pB.next == None:
19                 return None
20             if pA.next:
21                 pA = pA.next
22             else:
23                 pA = headB
24             if pB.next:
25                 pB = pB.next
26             else:
27                 pB = headA 
28         return pA