题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://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) {
if(pHead1 == nullptr || pHead2 == nullptr){
return nullptr;
}
ListNode *cur1=pHead1;
ListNode *cur2=pHead2;
int n=0;
while(cur1->next ){
cur1 = cur1->next;
n++;
}
while(cur2->next ){
cur2 = cur2->next;
n--;
}
if(cur1 != cur2){
return nullptr;
}
cur1 = n>0 ? pHead1:pHead2;
cur2 = cur1==pHead1?pHead2:pHead1;
n = abs(n);
while(n){
cur1=cur1->next;
n--;
}
while(cur1 != cur2){
cur1 = cur1->next;
cur2 = cur2->next;
}
return cur1;
}
};

