代码随想录算法【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();
    }
};
相关推荐
lastknight7 分钟前
CSS @layer
前端·css
李宸净9 分钟前
Web自动化测试selenium+python
前端·python·selenium
wear工程师20 分钟前
CompletableFuture 的 allOf 到底怎么收结果?面试别只说并行
java·后端
倒流时光三十年27 分钟前
Logback 系列(3):三大核心组件 Logger / Appender / Encoder
java·开发语言·logback
什巳35 分钟前
JAVA练习312- 二叉搜索树中第 K 小的元素
java·数据结构·算法·leetcode
淡海水41 分钟前
06-04-YooAsset源码-Unity加密解密服务
前端·unity·性能优化·c#·游戏引擎·yooasset
froyoisle1 小时前
CSP 真题解析:[CSP-J 2020-T3] 表达式
c++·算法·csp·信息学·信奥赛
geats人山人海1 小时前
算法好题 2026.7.18
算法
文祐1 小时前
C++类之虚函数表没有虚继承的菱形继承
开发语言·c++·算法
Lumos1861 小时前
51单片机从零到实战(8)——串口通信
算法