(哈希表) $O(n+m)$
用一个哈希表记下访问过的指针
C++ 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *findFirstCommonNode(ListNode *headA, ListNode *headB) {
map<ListNode*,int> record;
int cnt = 0;
ListNode* h = headA;
while(h!=NULL){
record[h] = 1;
h = h->next;
}
h = headB;
while(h!=NULL){
if (record[h]) return h;
h = h->next;
}
return NULL;
}
};