225. Implement Stack using Queues这里使用队列实现stack,使用c++ stl中的deque.

class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        stack.push_back(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int val = stack.back();
        stack.pop_back();
        return val;
    }
    
    /** Get the top element. */
    int top() {
        return stack.back();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return stack.empty();
    }
private:
    deque<int> stack;
};

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

运行结果:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Implement Stack using Queues.
Memory Usage: 7 MB, less than 100.00% of C++ online submissions for Implement Stack using Queues.