代码随想录算法【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();
    }
};
相关推荐
爱coding的橙子2 小时前
每日算法刷题 Day3 5.11:leetcode数组2道题,用时1h(有点慢)
算法·leetcode
Chase_Mos3 小时前
Spring 必会之微服务篇(1)
java·spring·微服务
小林学习编程5 小时前
SpringBoot校园失物招领信息平台
java·spring boot·后端
撸码到无法自拔5 小时前
docker常见命令
java·spring cloud·docker·容器·eureka
蓝婷儿5 小时前
前端面试每日三题 - Day 32
前端·面试·职场和发展
heart000_15 小时前
IDEA 插件推荐:提升编程效率
java·ide·intellij-idea
ŧ榕树先生6 小时前
查看jdk是否安装并且配置成功?(Android studio安装前的准备)
java·jdk
星空寻流年6 小时前
CSS3(BFC)
前端·microsoft·css3
未来的JAVA高级开发工程师6 小时前
适配器模式
java
九月TTS6 小时前
开源分享:TTS-Web-Vue系列:Vue3实现固定顶部与吸顶模式组件
前端·vue.js·开源