Description
编写一个程序,找到两个单链表相交的起始节点。
Solution 1
暴力法,遍历A链表的每一个节点在B链表中依次判断是否是公共节点。
Solution 2
hashmap,遍历A链表将每个节点保存在hashmap中,再遍历B链表每个节点判断是否在hashmap中出现过。
Solution 3
class Solution(object):
def getIntersectionNode(self, headA, headB):
ha, hb = headA, headB
while ha != hb:
# if ha 而不是 if ha.next 这样可以处理两个不相交链表的情况
ha = ha.next if ha else headB
hb = hb.next if hb else headA
return ha