leetcode

225.用队列实现栈

力扣链接

class MyStack {
public:
    std::queue<int> que;
    MyStack(){}
    
    void push(int x) {
        // queue里的push从队列的back加而非front,不像stack的push和top是同一个位置
        que.push(x);
    }

    int top() {
        // top()不受pop()影响
        return que.back();
    }

    // queue 是基于其他容器(默认情况下是 std::deque)实现的 适配器容器
    // queue容器基于先进先出原则,无法直接删除队列末尾元素。deque可以
    int pop() {
        int size = que.size();
        size--;
        while(size--){
            que.push(que.front());
            que.pop();
        }
        int res = que.front();
        que.pop();
        return res;
    }
    
    bool empty() {
        return que.empty();
    }
};

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