两个链表的第一个公共结点 ----《剑指offer》面试题37

题目

输入两个链表,找出它们的第一个公共结点。

思路

(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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值