代码随想录算法【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();
    }
};
相关推荐
A24207349303 分钟前
React中请求拦截与响应拦截的统一处理方案
前端·javascript·react.js
mister_guo4 分钟前
Java线程池参数应该如何设置(ThreadPoolExecutor)
java
余额瞒着我当琳4 分钟前
C++模板初阶与STL初探
android·java·c++
淡海水13 分钟前
15-02-YooAsset面试篇-Unity架构设计与源码
java·unity·面试·c#·游戏引擎·yooasset
weixin_BYSJ198732 分钟前
springboot酒店管理系统--附源码27436
java·spring boot·python·随机森林·贪心算法·eclipse·django
嵌入式老牛33 分钟前
三相电气量采集模块设计(三)非同步采样时的精度提升
算法·精度·计量
2401_8949155336 分钟前
GEO 源码部署如何实现精准地域分发?核心配置参数深度讲解
java·运维·服务器·后端·开源
IT_陈寒39 分钟前
为什么我的Java Stream流操作会吃掉内存?
前端·人工智能·后端
今天AI了吗1 小时前
精细化落地教程:TimechoAI调参标准+数据清洗规范+误差归因+阈值适配全维度指南
大数据·人工智能·算法
嘟嘟07172 小时前
React 受控组件与非受控组件:表单数据到底归谁管?
前端·javascript·react.js