题目
输入两个链表,找出它们的第一个公共结点。
思路
(1)将两个链表A、B分别压入两个不同的栈中。
(2)两个栈同时弹出栈顶元素进行比较,直到找到最后一个相同的栈顶元素,就是A、B两个链表中的第一个公共结点。
代码
#include <iostream>
#include <stack>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
ListNode* FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2)
{
if (pHead1 == nullptr || pHead2 == nullptr)
return nullptr;
// 分别将A、B两个链表压入栈中
stack<ListNode*> stack1,stack2;
ListNode* p = pHead1;
while (p)
{
stack1.push(p);
p = p->m_pNext;
}
p = pHead2;
while (p)
{
stack2.push(p);
p = p->m_pNext;
}
// 对两个栈的栈顶元素进行对比,取最后一个相同的顶元素作为A、B链表的第一个公共节点
ListNode* pCommon = nullptr;
ListNode* pNode1 = nullptr;
ListNode* pNode2 = nullptr;
while (!stack1.empty() || !stack2.empty())
{
pNode1 = stack1.top();
pNode2 = stack2.top();
if (pNode1 == pNode2)
{
pCommon = pNode1;
stack1.pop();
stack2.pop();
}
else
break;
}
return pCommon;
}
int main()
{
ListNode A5{5, nullptr};
ListNode A4{4, &A5};
ListNode A3{3, &A4};
ListNode A2{2, &A3};
ListNode A1{1, &A2};
ListNode B2{12, &A4};
ListNode B1{11, &B2};
ListNode* ans = FindFirstCommonNode(&A1, &B1);
if (ans)
cout << "The common node of A and B is: "
<< ans->m_nKey << endl;
else
cout << "There is no common node of A and B" << endl;
return 0;
}