【leetcode】用栈实现队列

题目链接:232. 用栈实现队列 - 力扣(LeetCode)

栈虽是先进后出,用一个栈可以将序列倒序,那么再用一个栈就可以正序了

先用一个栈存储进来的,要输出的时候再用一个栈装一下

复制代码
class MyQueue {
public:
    stack<int> in;
    stack<int> out;

    void inToOut() {
        while (!in.empty()) {
            out.push(in.top());
            in.pop();
        }
    }

    MyQueue() {

    }

    void push(int x) {
        in.push(x);
    }

    int pop() {
        int top = peek();
        out.pop();
        return top;
    }

    int peek() {
        if (out.empty())
            inToOut();
        return out.top();
    }

    bool empty() {
        return in.empty() && out.empty();
    }
};
相关推荐
北顾笙98012 小时前
day22-数据结构力扣
数据结构·算法·leetcode
IT枫斗者12 小时前
AI Agent 设计模式全景解析:从单体智能到分布式协作的架构演进
人工智能·redis·分布式·算法·spring·缓存·设计模式
2301_8227032012 小时前
鸿蒙flutter三方库适配——笔记与知识管理应用:Flutter Markdown实战
笔记·算法·flutter·华为·图形渲染·harmonyos·鸿蒙
人道领域12 小时前
【LeetCode刷题日记】454:四数相加Ⅱ
算法·leetcode
她说彩礼65万12 小时前
C语言 指针运算
c语言·数据结构·算法
skilllite作者12 小时前
自进化 Agent 的 skills 别长成烟囱:从多入口分叉到统一发现与 spec 防火带
人工智能·算法·rust·openclaw·agentskills
kaikaile199512 小时前
移动机器人路径跟踪的设计与仿真:模型预测控制(MPC)详解
人工智能·stm32·嵌入式硬件·算法
进击的荆棘13 小时前
递归、搜索与回溯——递归
算法·leetcode·递归
2301_8227032014 小时前
鸿蒙Flutter第三方库FlutterUnit组件百科适配——具体示例还原演示1
算法·flutter·华为·harmonyos·鸿蒙
2301_7644413321 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法