leetcode

232.用栈实现队列

力扣题目链接

class MyQueue {
public:
    std::stack<int> inst, outst;
    MyQueue() {}

    void push(int x) {
        inst.push(x);
    }
    
    int pop() {
        if(outst.empty()){
            while(!inst.empty()){
                outst.push(inst.top());
                inst.pop();
            }
        }
        int res = outst.top();
        outst.pop();
        return res;
    }
    
    int peek() {
        // 也可 int res = pop(); *
        int res = this->pop();
        outst.push(res);
        return res;
    }
    
    bool empty() {
        return inst.empty() && outst.empty();
    }
};

/**
 * 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();
 */