Clean 0 ms C++ solution using 2 stacks


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

Log in to reply
 

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