Accepted 0ms C++ solution


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

Log in to reply
 

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