输入两个链表,找出它们的第一个公共结点。
注意:公共节点指的是它们的尾部相同,而不仅仅是值相等
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1==NULL||pHead2==NULL)
return NULL;
int n1=0,n2=0;
ListNode* p1=pHead1;
ListNode* p2=pHead2;
while(p1!=NULL){
++n1;
p1=p1->next;
}
while(p2!=NULL){
++n2;
p2=p2->next;
}
p1=pHead1;p2=pHead2;
if(n1>n2){
int d=n1-n2;
while(d--)
p1=p1->next;
}
else if(n2>n1){
int d=n2-n1;
while(d--)
p2=p2->next;
}
while(p1->val!=p2->val&&p1!=NULL){
p1=p1->next;
p2=p2->next;
}
return p1;
}
};