My c++ solution with comments


  • 0
    class Queue {
    private:
        stack<int> input, output;
    public:
        // Push element x to the back of queue.
        void push(int x) {
            input.push(x);
        }
        
        /*when popping with a empty output-stack, pouring input to output*/
        void pouring(stack<int>& input, stack<int>& output){
            if(output.empty()){//check if need before real operation
                 while(!input.empty()){
                    output.push(input.top());
                    input.pop();
                }
            }
        }
        
        // Removes the element from in front of queue.
        void pop(void) {
            pouring(input, output);
            output.pop();           
        }
    
        // Get the front element.
        int peek(void) {
            pouring(input, output);
            return output.top();
        }
    
        // Return whether the queue is empty.
        bool empty(void) {
            return input.empty() && output.empty();
        }
    };

Log in to reply
 

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