关闭

37.两个链表的第一个公共结点

标签: 链表
357人阅读 评论(0) 收藏 举报
分类:

题目:输入两个链表,找出它们的第一个公共结点,链表结点定义如下:

struct  ListNode

{

         int m_nKey;

         ListNode*  m_pNext;

};



ListNode* FindFirstComonNode(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 = nLength1 - nLength2;
}
//先在长链表上走几步,再同时在两个链表上遍历
for (int i = 0; i < nLengthDif; ++i)
pListHeadLong = pListHeadLong->m_pNext;
while ((pListHeadLong != NULL) && (pListHeadShort != NULL) && (pListHeadLong!=pListHeadShort)
{
pListHeadLong = pListHeadLong->m_pNext;
pListHeadShort = pListHeadShort->m_pNext;
}
//得到第一个公共结点
ListNode* pFirstCommonNode = pListHeadLong;
return pFirstCommonNode;
}
unsigned  int GetListLength(ListNode* pHead)
{
unsigned int nLength = 0;
ListNode* pNode = pHead;
while (pNode != NULL)
{
++nLength;
pNode = pNode->m_pNext;
}
return nLength;
}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:157223次
    • 积分:6155
    • 等级:
    • 排名:第4035名
    • 原创:479篇
    • 转载:2篇
    • 译文:1篇
    • 评论:3条
    最新评论