这里的公共节点指的是值(val)相等的节点,并不一定是同一个节点。
用一个set存储查找过的节点,直到发现重复的即公共节点。
直接上代码。
/*
struct ListNode {int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
set<ListNode *> s;
while(pHead1 || pHead2)
{
if(pHead1)
{
if(s.find(pHead1) == s.end())
{
s.insert(pHead1);
pHead1 = pHead1 -> next;
}
else return pHead1;
}
if(pHead2)
{
if(s.find(pHead2) == s.end())
{
s.insert(pHead2);
pHead2 = pHead2 -> next;
}
else return pHead2;
}
}
return NULL;
}
};