力扣 232用栈实现队列

思路:

栈的特性是先进后出,队列是先进先出

因此用两个栈来模拟队列

要实现的功能包括

push 入队列

pop() 出队列

peek获取队列的最上元素

isempty 队列判空

push 正常操作 stin.push(),只要元素入栈就行,stout元素入栈是其他步骤的事

pop()出队列,思路是,当stout为空时,依次弹出stin上方元素知道stin为空,弹出最上面元素包含两步先获取最上面的元素top(),再弹出pop()

peek获取最上元素,复用int result = this->pop()因为这一步的弹出,再把元素放回 stout.push(result) 返回该元素return result

判空,如果两个栈都是空的,那么就空了

复制代码
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();
    }
};
相关推荐
Xの哲學几秒前
Linux NAPI 架构详解
linux·网络·算法·架构·边缘计算
京东零售技术3 小时前
扛起技术大梁的零售校招生们 | 1024技术人特别篇
算法
爱coding的橙子4 小时前
每日算法刷题Day78:10.23:leetcode 一般树7道题,用时1h30min
算法·leetcode·深度优先
Swift社区4 小时前
LeetCode 403 - 青蛙过河
算法·leetcode·职场和发展
地平线开发者4 小时前
三种 Badcase 精度验证方案详解与 hbm_infer 部署实录
算法·自动驾驶
papership4 小时前
【入门级-算法-5、数值处理算法:高精度的减法】
算法·1024程序员节
lingran__4 小时前
算法沉淀第十天(牛客2025秋季算法编程训练联赛2-基础组 和 奇怪的电梯)
c++·算法
DuHz5 小时前
基于MIMO FMCW雷达的二维角度分析多径抑制技术——论文阅读
论文阅读·物联网·算法·信息与通信·毫米波雷达
一二学长5 小时前
快速排序(JAVA详细讲解快速排序的四种方式)
数据结构
Dragon_D.5 小时前
排序算法大全——插入排序
算法·排序算法·c·学习方法