代码随想录算法【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();
    }
};
相关推荐
不知名的老吴13 分钟前
经典算法题之行星碰撞
数据结构·算法
布朗克16815 分钟前
39 Spring Boot Web实战
前端·spring boot·后端·实战
gaohe26AIliuzeyu15 分钟前
Java内部类
java·开发语言
西安邮电大学19 分钟前
有关数组的经典算法题
java·后端·其他·算法·面试
互联网推荐官23 分钟前
上海AI Agent智能体开发公司技术选型实录:六条路径、三类架构与真实落地约束
java·人工智能·ai·架构·开发经验·上海
学Linux的语莫24 分钟前
大模型微调数据集格式详解:Alpaca、ShareGPT、DPO、KTO、预训练数据怎么构建?
人工智能·算法·机器学习·微调格式
纽格立科技25 分钟前
DRM 发射端链路图(上)
前端·人工智能·车载系统·信息与通信·传媒
wayz1126 分钟前
Momentum:UO(终极震荡指标)技术指标详解
算法·金融·数据分析·量化交易·特征工程
mikasa66730 分钟前
关于Spring MVC 基于 AOP 实现的全局控制器统一处理方案@ControllerAdvice
java·spring·mvc
一 乐31 分钟前
幼儿园管理系统|基于springboot + vue幼儿园管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·幼儿园管理系统