题目:输入两个链表,找出它们的第一个公共结点。
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2)
{
unsigned int nLength1 = getListLength(pHead1);
unsigned int nLength2 = getListLength(pHead2);
int nLengthDif = nLength1 - nLength2;
ListNode* pListHeadLong = pHead1;
ListNode* pListHeadShort = pHead2;
if (nLength2 > nLength1)
{
pListHeadLong = pHead2;
pListHeadShort = pHead1;
nLengthDif = nLength2 - nLength1;
}
for (int i = 0;i < nLengthDif;++i)
{
pListHeadLong = pListHeadLong->next;
}
while ((pListHeadLong != nullptr) && (pListHeadShort != nullptr) && (pListHeadLong != pListHeadShort))
{
pListHeadLong = pListHeadLong->next;
pListHeadShort = pListHeadShort->next;
}
ListNode* pFirstCommonNode = pListHeadLong;
return pFirstCommonNode;
}
unsigned int getListLength(ListNode* pHead)
{
unsigned int length = 0;
ListNode* pNode = pHead;
while (pNode != nullptr)
{
++length;
pNode = pNode->next;
}
return length;
}