Share my C++ solution with two queue.


  • 0
    A
    class Stack {
    public:
        // Push element x onto stack.
    
        void push(int x) {
            q1.push(x);
        }
    
        // Removes the element on top of the stack.
        void pop() {
            if(q1.empty())
                return;
            while(q1.size() > 1)
            {
                q2.push(q1.front());
                q1.pop();
            }
            q1.pop();
            swap(q1, q2);
        }
    
        // Get the top element.
        int top() {
            if(q1.empty())
                return -1;
            while(q1.size() > 1)
            {
                q2.push(q1.front());
                q1.pop();
            }
            int ret = q1.front();
            q1.pop();
            q2.push(ret);
            swap(q1, q2);
            return ret;
            
        }
    
        // Return whether the stack is empty.
        bool empty() {
            return q1.empty();
        }
        private:
            queue<int> q1;
            queue<int> q2;
    };

Log in to reply
 

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