/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
int GetListLen(ListNode* pHead) {
int len = 0;
while (pHead) {
len += 1;
pHead = pHead->next;
}
return len;
}
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
int len1 = GetListLen(pHead1);
int len2 = GetListLen(pHead2);
int diff = abs(len1 - len2); // 获取两个链表长度差
// 确定长链表的头,先走diff步
ListNode* pLonger = pHead1;
ListNode* pShorter = pHead2;
if (len2 > len1) {
pLonger = pHead2;
pShorter = pHead1;
}
while (diff-- > 0) {
pLonger = pLonger->next;
}
while (pLonger && pShorter && pLonger != pShorter) {
pLonger = pLonger->next;
pShorter = pShorter->next;
}
return pLonger;
}
};