剑指offer 5:用两个栈实现队列

本文介绍了一种使用两个栈来实现队列数据结构的方法。通过将一个栈作为输入栈,另一个栈作为输出栈,可以有效地模拟队列的先进先出特性。当需要从队列中取出元素时,如果输出栈为空,则将所有输入栈的元素依次弹出并压入输出栈,再从输出栈中弹出元素,从而实现队列的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stack>

using namespace std;

class Solution
{
public:
    void push(int node) {
        stackIn.push(node);//入栈
    }
    int pop() {
        int node = -1;
        if (this->empty() == true) { //判断两个栈是否为空
            cout << "null" << endl;
            return -1;
        }
        else {
            if (stackOut.empty() == true) { //输出栈为空,输入栈必不为空
                while(stackIn.empty() != true) {
                    node = stackIn.top();//把输入栈的元素压入输出栈
                    stackIn.pop();
                    stackOut.push(node);
                    cout << node << "导入输出栈" << endl;
                    //stackOut.push(stackIn.pop());
                }
            }
            //输出栈不为空,直接弹出
            else {
                node = stackOut.top();
                stackOut.pop();//pop
                cout << "队头元素" << node << endl;
            }
        }
        return node;
    }
    bool empty() {
        return (stackIn.empty() == true && stackOut.empty() == true);
    }
private:
    stack<int> stackIn;
    stack<int> stackOut;
};


int main()
{
    Solution solu;
    solu.push(1);
    solu.push(2);
    solu.push(3);
    solu.push(4);
    int node;
    while (solu.empty() != true) {
        cout << solu.pop();
    }

    return 0;
}






















































 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值