牛客题霸 [用两个栈实现队列] C++题解/答案

题目描述

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

题解:

我们都知道栈的性质是先进后出,队列是先进先出
我们用两个栈来模拟出队列
可以先用一个栈来存数,当要输出时,最上面的是最晚进栈的,我们将所有数存到另一个栈内,这样就使得第二个栈的顶部是最早输入的数,就可以实现先进先出

代码:

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

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

private:
    stack<int> stack1;
    stack<int> stack2;
};
posted @ 2020-11-08 22:53  回归梦想  阅读(52)  评论(0编辑  收藏  举报