LeetCode 232 Implement Queue using Stacks

标签: 设计数据结构 LeetCode 发布于:2022-02-11 14:07:59 编辑于:2022-02-11 14:16:58 浏览量:1030

概述

https://leetcode.com/problems/implement-queue-using-stacks/

双栈法

class MyQueue {
public:
    stack<int>* a;
    stack<int>* b;
    MyQueue() {
        this->a = new stack<int>;
        this->b = new stack<int>;
    }
    
    void push(int x) {
        a->push(x);
    }
    
    int pop() {
        return popOrPeek(true);
    }
    
    int peek() {
        return popOrPeek(false);
    }
    
    bool empty() {
        return a->empty() && b->empty();
    }
    
    int popOrPeek(bool isPop) {
        if (b->empty()) {
            while (!a->empty()) {
                b->push(a->top());
                a->pop();
            }
        }
        int top = b->top();
        if (isPop) b->pop();
        return top;
    }
};

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