代码随想录算法【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();
    }
};
相关推荐
weixin_5841214311 小时前
HTML+layui表单校验范围值,根据条件显示隐藏某输入框
前端·html·layui
加油乐11 小时前
react基础概念合集
前端·react.js
一只小小Java11 小时前
Java面试场景高频题
java·开发语言·面试
沛沛老爹11 小时前
Web开发者快速上手AI Agent:基于Function Calling的12306自动订票系统实战
java·人工智能·agent·web转型
CRUD酱11 小时前
后端使用POI解析.xlsx文件(附源码)
java·后端
亓才孓11 小时前
多态:编译时看左边,运行时看右边
java·开发语言
小白探索世界欧耶!~11 小时前
用iframe实现单个系统页面在多个系统中复用
开发语言·前端·javascript·vue.js·经验分享·笔记·iframe
bl4ckpe4ch11 小时前
用可复现实验直观理解 CORS 与 CSRF 的区别与联系
前端·web安全·网络安全·csrf·cors
苦藤新鸡11 小时前
6.三数之和
c语言·c++·算法·力扣
阿珊和她的猫11 小时前
Webpack中import的原理剖析
前端·webpack·node.js