您的位置:首页 > Web前端

剑指offer——两个链表的第一个公共结点

2014-09-09 15:02 337 查看
首先计算两个链表的长度m,n,让较长的链表先走|m-n|,然后两个链表一起走,直到找到元素相同的结点。

#include <iostream>
using namespace std;

ListNode
{
int m_data;
ListNode *m_next;
};

unsigned int GetListLength(ListNode* pHead)
{
unsigned int nLength=0;
ListNode* pNode=pHead;
while(pNode!=NULL)
{
++nLength;
pNode=pNode->m_next;
}
}

ListNode* FindFirstCommonNode(ListNode* pHead1,ListNode* pHead2)
{
unsigned int nLength1=GetListLength(pHead1);
unsigned int nLength2=GetListLength(pHead2);
int nLengthDif=nLength1-nLength2;
ListNode* pListLong=pHead1;
ListNode* pListShort=pHead2;
if (nLength2>nLength1)
{
pListLong=pHead2;
pListShort=pHead1;
nLengthDif=-nLengthDif;
}
for (int i=0;i<nLengthDif;i++)
{
pListLong=pListLong->m_next;
}
while((pListLong!=NULL)&&(pListShort!=NULL)&&(pListLong!=pListShort))
{
pListLong=pListLong->m_next;
pListShort=pListShort->m_next;
}
ListNode* pFirstCommonNode=pListLong;
return pFirstCommonNode;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: