题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ #include <unordered_map> #include <vector> class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { ListNode* temp =pHead1; unordered_map<ListNode*, int>mymap; if(pHead1==nullptr||pHead2==nullptr){return nullptr;} //开始分别遍历两个非空链表 //遍历第一个链表 while(pHead1!=nullptr){ mymap[pHead1]++; pHead1 = pHead1->next; } //遍历第一个链表 while(pHead2!=nullptr){ mymap[pHead2]++; pHead2 = pHead2->next; } //查看哈希表中首节点 while (temp!=nullptr) { if (mymap[temp]>1) { return temp; } temp=temp->next; } return nullptr; } };