LeetCode 225 Implement Stack using Queues

标签: 设计数据结构 LeetCode 发布于:2022-02-11 14:34:53 编辑于:2022-02-11 14:42:10 浏览量:945

概述

https://leetcode.com/problems/implement-stack-using-queues/

双队列法

无语了,实现过程中 b = temp 写成了 b = a,导致死循环 TLE。。。

class MyStack {
public:
    queue<int>* a;
    queue<int>* b;
    MyStack() {
        a = new queue<int>;
        b = new queue<int>;
    }
    
    void push(int x) {
        a->push(x);
    }
    
    int pop() {
        return popOrTop(true);
    }
    
    int top() {
        return popOrTop(false);
    }
    
    bool empty() {
        return a->empty() && b->empty();
    }
    
    int popOrTop(bool isPop) {
        while (a->size() != 1) {
            b->push(a->front());
            a->pop();
        }
        int res = a->front();
        if (!isPop) {
            b->push(a->front());
        }
        a->pop();
        auto temp = a;
        a = b;
        b = temp;
        return res;
    }
};

单队列法

边 pop 边 push,这样一个队列也是可以的哦。

未经允许,禁止转载,本文源站链接:https://iamazing.cn/