A Clean C++ Solution


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

Log in to reply
 

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