(本博客旨在个人总结回顾)
题目描述:
在输入两个链表,找出它们的第一个公共结点。链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
根据上面的链表的结点可以得到若两个链表有公共结点,那它们的示意图如下:
从而只要计算两条链表的长度,将较长链表先遍历至红色部分,然后红色部分的起点共同向后遍历,判断两个结点是否相同即可。
源码:
#include "stdafx.h"
#include<iostream>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
ListNode(int nKey, ListNode* pNext = NULL)
: m_nKey(nKey)
, m_pNext(pNext)
{
}
};
/*
* @name FindFirstCommonNode
* @brief 获取两链表的第一个共同结点
* @param [in] ListNode * pListA
* @param [in] ListNode * pListB
* @return ListNode*
*/
ListNode* FindFirstCommonNode(ListNode* pListA, ListNode* pListB)
{
ListNode* pTarget = NULL;
if (pListA != NULL && pListB != NULL)
{
int lengthA = 0;
int lengthB = 0;
ListNode* pIndexA = pListA;
ListNode* pIndexB = pListB;
while (pIndexA != NULL)
{
lengthA++;
pIndexA = pIndexA->m_pNext;
}
while (pIndexB != NULL)
{
lengthB++;
pIndexB = pIndexB->m_pNext;
}
pIndexA = pListA;
pIndexB = pListB;
while (lengthA != lengthB)
{
if (lengthA > lengthB)
{
pIndexA = pIndexA->m_pNext;
lengthA--;
}
else if (lengthA < lengthB)
{
pIndexB = pIndexB->m_pNext;
lengthB--;
}
}
while (pIndexA != pIndexB && pIndexA != NULL && pIndexB != NULL)
{
pIndexA = pIndexA->m_pNext;
pIndexB = pIndexB->m_pNext;
}
if (pIndexA == pIndexB)
{
pTarget = pIndexA;
}
}
return pTarget;
}
int _tmain(int argc, _TCHAR* argv[])
{
ListNode* pCommon = new ListNode(4);
pCommon->m_pNext = new ListNode(3);
ListNode* pTmp = new ListNode(5, pCommon);
pTmp = new ListNode(6, pTmp);
pTmp = new ListNode(7, pTmp);
pTmp = new ListNode(8, pTmp);
pTmp = new ListNode(9, pTmp);
pTmp = new ListNode(10, pTmp);
ListNode* pListA = pTmp;
pTmp = new ListNode(11, pCommon);
pTmp = new ListNode(12, pTmp);
pTmp = new ListNode(13, pTmp);
ListNode* pListB = pTmp;
ListNode* pTarget = FindFirstCommonNode(pListA, pListB);
if (pTarget != NULL)
{
cout << pTarget->m_nKey << endl;
}
else
{
cout << "无共同结点!" << endl;
}
pTarget = FindFirstCommonNode(NULL, pListB);
if (pTarget != NULL)
{
cout << pTarget->m_nKey << endl;
}
else
{
cout << "无共同结点!" << endl;
}
pTarget = FindFirstCommonNode(pListA, NULL);
if (pTarget != NULL)
{
cout << pTarget->m_nKey << endl;
}
else
{
cout << "无共同结点!" << endl;
}
system("pause");
return 0;
}
运行结果: