代码随想录算法【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();
    }
};
相关推荐
SimonKing13 分钟前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
摸鱼的春哥1 小时前
春哥的Agent通关秘籍13:实现RAG查询
前端·javascript·后端
明月_清风2 小时前
滚动锁定:用户向上翻看历史时,如何阻止 AI 新消息把它“顶”下去?
前端·javascript
明月_清风2 小时前
当高阶函数遇到 AI:如何自动化生成业务层面的逻辑拦截器
前端·javascript·函数式编程
NAGNIP10 小时前
轻松搞懂全连接神经网络结构!
人工智能·算法·面试
NAGNIP10 小时前
一文搞懂激活函数!
算法·面试
董董灿是个攻城狮11 小时前
AI 视觉连载7:传统 CV 之高斯滤波实战
算法
moshuying12 小时前
别让AI焦虑,偷走你本该有的底气
前端·人工智能
GIS之路13 小时前
ArcPy,一个基于 Python 的 GIS 开发库简介
前端