Implement Queue using Stacks栈和队列--力扣101算法题解笔记

11.3Implement Queue using Stacks栈和队列

题目描述

用栈来实现队列。

输入输出样例

数据结构调用样例:

cpp 复制代码
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false

题解

用两个栈来实现一个队列,达到先入先出的结果,所以必定要通过一个额外栈来翻转一次数组,这样让翻转过程既可以在插入时完成,也可以在取值时完成

cpp 复制代码
#include <iostream>
#include <stack>
using namespace std;

class MyQueue {
    stack<int> in, out;
public:
    MyQueue() {}

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

    int pop() {
        in2out();
        if (out.empty()) return -1; // 防御性编程:防止空队列弹出
        int x = out.top();
        out.pop();
        return x;
    }

    int peek() {
        in2out();
        if (out.empty()) return -1; // 防御性编程
        return out.top();
    }

    void in2out() {
        if (out.empty()) {
            while (!in.empty()) {
                int x = in.top();
                in.pop();
                out.push(x);
            }
        }
    }

    bool empty() {
        return in.empty() && out.empty();
    }
};

int main() {
    MyQueue queue;

    queue.push(1);
    queue.push(2);

    cout << "peek: " << queue.peek() << endl;   // 应输出 1
    cout << "pop: " << queue.pop() << endl;     // 应输出 1
    cout << "empty: " << (queue.empty() ? "false" : "true") << endl; // 应输出 false (因为还剩一个2)

    return 0;
}
相关推荐
To_OC2 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
Forever Nore5 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR6 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
今儿敲了吗6 小时前
CO——CPU
笔记
今儿敲了吗6 小时前
Python ——第三方包
笔记·python
吃着火锅x唱着歌7 小时前
Effective C++ 学习笔记 条款40 明智而审慎地使用多重继承
c++·笔记·学习
落知秋7 小时前
RUST中的trait是什么?
笔记·rust
Tisfy7 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
xian_wwq7 小时前
【学习笔记】Prompt Engineering 没死,只是它不再够用了-2/16
笔记·学习·prompt