代码随想录算法【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();
    }
};
相关推荐
小肝一下4 分钟前
每日两道力扣,day5
数据结构·c++·算法·leetcode·职场和发展·hot100
jiang_changsheng10 分钟前
亚马逊的2026年最新算法变革自然流量分发机制“文本匹配”到“多模态意图理解”的范式革命
大数据·算法·推荐算法
OOJO5 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
AI袋鼠帝5 小时前
火爆全网的Seedance2.0 十万人排队,我2分钟就用上了
前端
IT_陈寒5 小时前
React Hooks闭包陷阱:你以为的state可能早就过期了
前端·人工智能·后端
Jenlybein5 小时前
快速了解熟悉 Vite ,即刻上手使用
前端·javascript·vite
小码哥_常5 小时前
安卓开发避坑指南:全局异常捕获与优雅处理实战
前端
lihaozecq5 小时前
我用 1 天的时间 vibe coding 了一个多人德州扑克游戏
前端·react.js·ai编程
momo061175 小时前
AI Skill是什么?
前端·ai编程
言萧凡_CookieBoty5 小时前
用 AI 搞定用户系统:Superpowers 工程化开发教程
前端·ai编程