代码随想录算法【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();
    }
};
相关推荐
xa138508693 分钟前
ARCGIS PRO SDK 多边形四至点计算
算法·arcgis
阿蒙Amon12 分钟前
C#每日面试题-进程和线程的区别
java·面试·c#
一 乐13 分钟前
养老院信息|基于springboot + vue养老院信息管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
hopsky14 分钟前
mvn install 需要 手动清除 pom.lastUpdated
java·maven·mavbne
59803541515 分钟前
【java工具类】小数、整数转中文小写
android·java·开发语言
cike_y15 分钟前
Mybatis之作用域(Scope)和生命周期-解决属性名和字段名不一致的问题&ResultMap结果集映射
java·开发语言·数据库·tomcat·mybatis
捻tua馔...16 分钟前
mobx相关使用及源码实现
开发语言·前端·javascript
cypking17 分钟前
解决 TypeScript 找不到静态资源模块及类型声明问题
前端·javascript·typescript
想学后端的前端工程师19 分钟前
【Webpack构建优化实战指南:从慢到快的蜕变】
前端
IT_陈寒23 分钟前
JavaScript性能优化:我用这7个V8引擎冷门技巧将页面加载速度提升了40%
前端·人工智能·后端