Link to LeetCode Problem

S1: 优化模拟

维护两个栈,一个用来写 (push),一个用来读 (pop)。

往写栈中 push,从读栈中 pop。当读栈为空时,将写栈中的数据全部倒入读栈中。

class MyQueue {
public:
    MyQueue() {}
    
    void push(int x) {
        write_.push(x);
    }
    
    int pop() {
        if (read_.empty()) pour();
        int val = read_.top();
        read_.pop();
        return val;
    }
    
    int peek() {
        if (read_.empty()) pour();
        return read_.top();
    }
    
    bool empty() {
        return write_.empty() && read_.empty();
    }
private:
    void pour() {
        while (!write_.empty()) {
            read_.push(write_.top());
            write_.pop();
        }
    }

    stack<int> read_;
    stack<int> write_;
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */