代码随想录算法【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();
    }
};
相关推荐
Matrix_111 天前
第13篇:非线性位移场——漩涡、鱼眼、水波纹与球面化
图像处理·算法
lili00121 天前
Claude自动修Bug配置优化与避坑指南
java·人工智能·python·bug·ai编程
逻极1 天前
Java 从入门到精通:核心原理、最佳实践与性能优化
java·jvm·并发编程·集合框架
金牌归来发现妻女流落街头1 天前
【LeetCode 第207题】
算法·leetcode·拓扑·领接表
AI砖家1 天前
前端 JavaScript 异步处理全方案详解:从回调到 Observable
开发语言·前端·javascript
熬夜敲代码的猫1 天前
AVL树(C++详解版)
数据结构·c++·算法
用户713874229001 天前
构建现代 Web 应用的令牌安全体系:Refresh Token Rotation、HttpOnly Cookie 与 Grace Period 全解析
前端
摇滚侠1 天前
SpringBoot 内嵌 TongWeb 东方通替换 Tomcat
java·spring boot·spring
HeLiang71 天前
proguard 混淆 使用JDK17 的 springboot4 + JPA
java·spring boot·proguard
武子康1 天前
Java-10 深入浅出 MyBatis 一对多与多对多查询配置详解
java·后端