/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
//因为具有公共结点的两个链表从此节点开始指导最后,都相同,因此我们让较长链表先走到N步长,然后一起向后走,第一个结点
相同的节点就是所求;
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1==NULL||pHead2==NULL)
return NULL;
ListNode*p=pHead1,*q=pHead2;
int len1=0,len2=0,dif=0;
while(p!=NULL)
{
len1++;
p=p->next;
}
while(q!=NULL)
{
len2++;
q=q->next;
}
if(len1>len2)
{
dif=len1-len2;
int i=0;
while(i<dif)
{
pHead1=pHead1->next;
i++;
}
}
if(len1<len2)
{
dif=len2-len1;
int i=0;
while(i<dif)
{
pHead2=pHead2->next;
i++;
}
}
while(pHead1&&pHead2)
{
if(pHead1->val==pHead2->val)
return pHead1;
else
{
pHead1=pHead1->next;
pHead2=pHead2->next;
}
}
return NULL;
}
};