题目:
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null
。
答案:
方法一:利用哈希表,遍历一次headA,将其节点存储到哈希表中,再遍历一次headB,比较B中的节点是否已经在哈希表中。
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
s = set()
p, q = headA, headB
while p:
s.add(p)
p = p.next
while q:
if q in s:
return q
q = q.next
return None
方法二:栈,从后往前遍历两个链表,第一个不相等的节点就是我们要的结果。
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
s1 = []
s2 = []
p,q = headA, headB
while p:
s1.append(p)
p = p.next
while q:
s2.append(q)
q = q.next
i = len(s1)-1
j = len(s2)-1
ans = None
while i >= 0 and j >= 0 and s1[i]==s2[j]:
ans = s1[i]
i = i-1
j = j-1
return ans