Simple C++ solution with two stacks


  • 0
    D
    class Queue {
    public:
        // Push element x to the back of queue.
        void push(int x) {
            a.push(x);    
        }
    
        // Removes the element from in front of queue.
        void pop(void) {
            shuffle();
            b.pop();
        }
    
        // Get the front element.
        int peek(void) {
            shuffle();
            return b.top();    
        }
    
        // Return whether the queue is empty.
        bool empty(void) {
            return a.empty() && b.empty();
        }
    private:
        stack<int> a, b;
        
        void shuffle() {
            if (!b.empty()) { return; }
            while (!a.empty()) {
                b.push(a.top()), a.pop();
            }
        }
    };

Log in to reply
 

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