C++ 0ms two deques solution


  • 0
    class MyStack {
    public:
        deque<int>q1;
        deque<int>q2;
        /** Initialize your data structure here. */
        MyStack() {}
        
        /** Push element x onto stack. */
        void push(int x) {
            q1.push_back(x);
        }
        
        /** Removes the element on top of the stack and returns that element. */
        int pop() {
            while(q1.size()>1) q2.push_back(q1.front()),q1.pop_front();
            int num=q1.front();
            q1.pop_front();
            q1=q2;
            q2.clear();
            return num;
        }
        
        /** Get the top element. */
        int top() {
            int num=pop();
            q1.push_back(num);
            return num;
        }
        
        /** Returns whether the stack is empty. */
        bool empty() {
            return q1.empty();
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.