代码随想录算法【Day10】

今日只做一题,剩下的题后面补

232.用栈实现队列

复制代码
class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    /** Initialize your data structure here. */
    MyQueue() {

    }
    /** Push element x to the back of queue. */
    void push(int x) {
        stIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
        if (stOut.empty()) {
            // 从stIn导入数据直到stIn为空
            while(!stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }

    /** Get the front element. */
    int peek() {
        int res = this->pop(); // 直接使用已有的pop函数
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};
相关推荐
散峰而望11 小时前
C++数组(三)(算法竞赛)
开发语言·c++·算法·github
空空kkk11 小时前
SpringMVC——IO笔记
java·io
q***952211 小时前
SpringMVC 请求参数接收
前端·javascript·算法
|晴 天|11 小时前
Vite 为何能取代 Webpack?新一代构建工具的崛起
前端·webpack·node.js
带只拖鞋去流浪11 小时前
迎接2026,重新认识Webpack5
前端·webpack
初级炼丹师(爱说实话版)11 小时前
多进程与多线程的优缺点及适用场景总结
算法
HIT_Weston11 小时前
43、【Ubuntu】【Gitlab】拉出内网 Web 服务:静态&动态服务
前端·ubuntu·gitlab
LucidX11 小时前
Web——反向代理、负载均衡与 Tomcat 实战部署
前端·tomcat·负载均衡
lcu11111 小时前
Java 学习40:继承
java
hetao173383711 小时前
2025-11-25~26 hetao1733837的刷题记录
c++·算法