/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
size_t getLengthOfList(ListNode *head)
{
size_t res = 0;
while(head != nullptr)
{
res++;
head = head->next;
}
return res;
}
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1 == nullptr || pHead2 == nullptr)
return nullptr;
size_t len1 = getLengthOfList(pHead1);
size_t len2 = getLengthOfList(pHead2);
ListNode *p1 = pHead1;
ListNode *p2 = pHead2;
if(len1 > len2)
{
int count = len1 - len2;
while(count-- > 0)
{
p1 = p1->next;
}
}
else if(len1 < len2)
{
int count = len2 - len1;
while(count-- > 0)
{
p2 = p2->next;
}
}
while(p1 != nullptr && p2 != nullptr)
{
if(p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
}
else
{
return p1;
}
}
return nullptr;
}
};