代码随想录算法【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();
    }
};
相关推荐
风之舞_yjf几秒前
Vue基础(14)_列表过滤、列表排序
前端·javascript·vue.js
你不是我我22 分钟前
【Java开发日记】说一说 SpringBoot 中 CommandLineRunner
java·开发语言·spring boot
yuan1999723 分钟前
Spring Boot 启动流程及配置类解析原理
java·spring boot·后端
2301_8076064325 分钟前
Java——抽象、接口(黑马个人听课笔记)
java·笔记
BillKu40 分钟前
scss(sass)中 & 的使用说明
前端·sass·scss
楚歌again41 分钟前
【如何在IntelliJ IDEA中新建Spring Boot项目(基于JDK 21 + Maven)】
java·spring boot·intellij-idea
酷爱码41 分钟前
IDEA 中 Maven Dependencies 出现红色波浪线的原因及解决方法
java·maven·intellij-idea
疯狂的沙粒44 分钟前
uni-app 项目支持 vue 3.0 详解及版本升级方案?
前端·vue.js·uni-app
Jiaberrr1 小时前
uniapp Vue2 获取电量的独家方法:绕过官方插件限制
前端·javascript·uni-app·plus·电量
Magnum Lehar1 小时前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎