力扣 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();
    }
};
相关推荐
钓鱼的肝35 分钟前
题单:归并排序
c++·算法
Sun_light1 小时前
队列:先进先出的线性数据结构及其应用
前端·javascript·算法
吕小鸣2 小时前
Coze、Dify、FastGPT三大AI智能平台架构与能力对比
算法
jndingxin2 小时前
c++ 面试题(1)-----深度优先搜索(DFS)实现
c++·算法·深度优先
北极的树2 小时前
谁说AI只会模仿,从Google AlphaEvolve项目看算法的自主创新
人工智能·算法·gemini
Watink Cpper2 小时前
[灵感源于算法] 算法问题的优雅解法
linux·开发语言·数据结构·c++·算法·leetcode
-qOVOp-2 小时前
408第一季 - 数据结构 - 折半查找与二叉排序树
数据结构
随意0232 小时前
STL 3算法
开发语言·c++·算法
_风满楼3 小时前
如何优雅展示日历中的重叠日程?三步搞定复杂布局
前端·javascript·算法
এ᭄画画的北北4 小时前
力扣-35.搜索插入位置
数据结构·算法·leetcode