1.蛮力法。O(m*n)
两层for循环遍历两个链表一个个匹配。
2.空间换时间。牛客网签到。
分析:先遍历一个链表存放在hash表中,在顺序遍历另一个链表同时查看hash表中是否存在,存在就是公共节点,直接返回。
c++ code:
class Solution {
public:
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == nullptr || pHead2 == nullptr)return nullptr;
ListNode*p1 = pHead1;
ListNode*p2 = pHead2;
map<int, int>MList;
while (p1)
{
MList[p1->val]++;
p1=p1->next;
}
while (p2)
{
if (MList[p2->val])
return p2;
p2=p2->next;
}
return nullptr;
}
};