代码随想录算法【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();
    }
};
相关推荐
mask哥1 小时前
详解flink性能优化
java·大数据·微服务·性能优化·flink·kafka·stream
hqxstudying1 小时前
Kafka 深入研究:从架构革新到性能优化的全面解析
java·开发语言·微服务·kafka·springcloud
浊浪载清辉1 小时前
《Html泛型魔法学院:用霍格沃茨风格网页教授集合框架》
前端·javascript·学习·html
limengshi1383921 小时前
人工智能学习:LR和SVM的联系与区别?
人工智能·算法·机器学习·支持向量机
Want5951 小时前
HTML元素周期表
前端·html
失散132 小时前
并发编程——17 CPU缓存架构详解&高性能内存队列Disruptor实战
java·缓存·架构·并发编程
一只一只妖4 小时前
突发奇想,还未实践,在Vben5的Antd模式下,将表单从「JS 配置化」改写成「模板可视化」形式(豆包版)
前端·javascript·vue.js
点云SLAM6 小时前
PyTorch 中.backward() 详解使用
人工智能·pytorch·python·深度学习·算法·机器学习·机器人
only-qi6 小时前
146. LRU 缓存
java·算法·缓存
悟能不能悟6 小时前
js闭包问题
开发语言·前端·javascript