My C++ solution using two queue.


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

    The time complexity of pop() and top() is O(n).


Log in to reply
 

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