C++ two stacks solution, concise and fast


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

Log in to reply
 

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