LeetCode 225. 用队列实现栈

思路:
一个队列用于备份,先将原队列最后一位元素之前的元素弹出,push进备份队列,后再还原

class MyStack {
public:
    queue<int> queue1;
    queue<int> queue2; //备份
    MyStack() {

    }
    
    void push(int x) {
        queue1.push(x);
    }
    
    int pop() {
        int res;
        int n = queue1.size() - 1;
        while (n --) {
            queue2.push(queue1.front());
            queue1.pop();
        }

        res = queue1.front();
        queue1.pop();

        while (queue2.size()) {
            queue1.push(queue2.front());
            queue2.pop();
        }

        return res;
    }
    
    int top() {
        int res = pop();
        queue1.push(res);

        return res;
    }
    
    bool empty() {
        return queue1.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
posted @   hjy94wo  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示