LeetCode 232. 用栈实现队列

思路:
用两个栈实现队列
pop操作,若out栈为空则先将in中元素push进out,再pop出out中元素
peek操作,直接调用pop,在将pop出元素push进out

class MyQueue {
public:
    stack<int> in;
    stack<int> out;
    MyQueue() {

    }
    
    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        int res;
        if (out.empty()) {
            while (in.size()) {
                out.push(in.top());
                in.pop();
            }
        }

        res = out.top();
        out.pop();

        return res;
    }
    
    int peek() {
        int res = pop();
        out.push(res);

        return res;
    }
    
    bool empty() {
        return in.empty() && out.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */
posted @   hjy94wo  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示