题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
int length1=0;
int length2=0;
auto p1 = pHead1;
auto p2 = pHead2;
while(p1!=NULL){
length1++;
p1=p1->next;
}
while(p2!=NULL){
length2++;
p2=p2->next;
}
int length = abs(length1 - length2);
if(length1 > length2){
for(int i=0;i<length;i++)pHead1=pHead1->next;
while(pHead1!=pHead2){
pHead1=pHead1->next;
pHead2=pHead2->next;
}
}
else{
for(int i=0;i<length;i++)pHead2=pHead2->next;
while(pHead1!=pHead2){
pHead1=pHead1->next;
pHead2=pHead2->next;
}
}
return pHead1;
}
};


