所有代码均通过G++编译器测试,仅为练手纪录。
//面试题37:两个链表的第一个公共结点
//题目:输入两个链表,找出它们的第一个公共结点。
//面试题37:两个链表的第一个公共结点
//题目:输入两个链表,找出它们的第一个公共结点。
int GetListLength(ListNode *pHead)
{
int nLength = 0;
ListNode *pNode = pHead;
while(NULL != pNode)
{
pNode = pNode->m_pNext;
++nLength;
}
return nLength;
}
ListNode* FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2)
{
if(NULL == pHead1 || NULL == pHead2)
{
return NULL;
}
int nLen1 = GetListLength(pHead1);
int nLen2 = GetListLength(pHead2);
int nLenDiff = nLen1 - nLen2;
ListNode *pHeadLong = pHead1;
ListNode *pHeadShort = pHead2;
if(nLenDiff < 0)
{
pHeadLong = pHead2;
pHeadShort = pHead1;
nLenDiff = nLen2 - nLen1;
}
while (nLenDiff--)
{
pHeadLong = pHeadLong->m_pNext;
}
while (NULL != pHeadLong && pHeadLong != pHeadShort)
{
pHeadLong = pHeadLong->m_pNext;
pHeadShort = pHeadShort->m_pNext;
}
return pHeadLong;
}
ZhaiPillary
2017-01-07