/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
//处理边界
//cout<<"o";
if(!pHead1||!pHead2) return NULL;
//先计算两者的长度
int l1=1,l2=1;
ListNode* p1=pHead1,*p2=pHead2;
while(p1)
{
p1=p1->next;
l1++;
}
while(p2)
{
p2=p2->next;
l2++;
}
p1=pHead1,p2=pHead2;
cout<<l1<<l2;
//长的先走
int d=l1-l2;
if(d>0)
{
while(d--)
{
p1=p1->next;
}
}
else
{
d=-d;
while(d--)
{
p2=p2->next;
}
}
//一起走
while(p1&&p2&&p1!=p2)
{
if(p1==p2)
{
break;
}
p1=p1->next;
p2=p2->next;
}
if(p1==p2)
{
return p1;
}
return NULL;
}
};