JZ9 用两个栈实现队列

image
image

class Solution
{
public:
    //用两个栈实现 队列 栈是先进后出,队列是先进先出
    //在队列尾部插入整数
    void push(int node) {
        //入队就正常入栈
        stack1.push(node);
    }
    //在队列头部删除整数,先进先出
    int pop() {
        //将第一个栈中内容弹出放入第二个栈中
        while(!stack1.empty())
        {
            stack2.push(stack1.top());
            stack1.pop();
        }
        //第二个栈栈顶就是最先进来的元素,即队首
        int res = stack2.top();
        stack2.pop();

        //再将第二个栈的元素放回第一个栈
        //这样使得第一个栈中虽然取得了最里面的元素,但是顺序并没有改变
        while(!stack2.empty())
        {
            stack1.push(stack2.top());
            stack2.pop();
        }
        return res;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

posted @ 2024-04-24 21:47  蓝色的海嗷  阅读(65)  评论(0)    收藏  举报