代码随想录算法【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();
    }
};
相关推荐
yi.Ist3 分钟前
数据结构 —— 键值对 map
数据结构·算法
s153355 分钟前
数据结构-顺序表-猜数字
数据结构·算法·leetcode
星辰离彬6 分钟前
Java 与 MySQL 性能优化:MySQL连接池参数优化与性能提升
java·服务器·数据库·后端·mysql·性能优化
半桔6 分钟前
【Linux手册】从接口到管理:Linux文件系统的核心操作指南
android·java·linux·开发语言·面试·系统架构
Coding小公仔8 分钟前
LeetCode 8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
GEEK零零七14 分钟前
Leetcode 393. UTF-8 编码验证
算法·leetcode·职场和发展·二进制运算
nightunderblackcat15 分钟前
新手向:实现ATM模拟系统
java·开发语言·spring boot·spring cloud·tomcat·maven·intellij-idea
江号软件分享18 分钟前
有效保障隐私,如何安全地擦除电脑上的敏感数据
前端
Bug退退退12320 分钟前
RabbitMQ 高级特性之延迟队列
java·spring·rabbitmq·java-rabbitmq