代码随想录算法【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();
    }
};
相关推荐
JWASX几秒前
【RocketMQ 生产者和消费者】- 事务消息的使用
java·rocketmq·java-rocketmq
Via_Neo1 分钟前
接雨水问题 + 输入优化
java·开发语言·算法
Cg136269159743 分钟前
JS函数表示
前端·html
xufengzhu3 分钟前
多层Module依赖项目Maven编译错误的解决方案
java·maven
吃鱼不吐刺.4 分钟前
阻塞队列。
java·开发语言
啦啦啦_99994 分钟前
3. AI面试题之 FunctionCall
java
半夜修仙4 分钟前
总结一下 Spring 中存取 Bean 的相关注解, 以及这些注解的用法.
java·笔记·学习·spring
彭于晏Yan5 分钟前
Spring Cloud Security:Oauth2令牌存储
java·spring boot·spring cloud
不光头强6 分钟前
ArrayList知识点
java·开发语言·windows
plus4s6 分钟前
3月13日(进阶5)
算法