剑指offer-用两个栈实现队列

前提是你 提交于 2020-01-10 11:05:10

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型

思路

一个栈用来存放,另一个栈用来输出,输出的时候注意要将输出栈的全部内容输出完毕后才能填充数据

AC代码

#include <iostream>
#include <stack>
using namespace std;

class Solution
{
public:
    void push(int node)
    {
        stack1.push(node);
    }

    int pop()
    {
        while (1)
        {
            if (!stack2.empty())
            {
                int y = stack2.top();
                stack2.pop();
                return y;
            }
            while (!stack1.empty())
            {
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
int main()
{
    Solution a;
    cout << "11122" << endl;
    a.push(1);
    a.push(2);
    
    cout << a.pop() << endl;
    a.push(3);
    cout << a.pop() <<endl;
    cout << a.pop() <<endl;
    cout << "111" << endl;
    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!