Accepted clean C++ solution


  • 0
    A

    When stack output is empty,pop elements from stack input and push them into output then pop stack output,else just pop stack output.

    class Queue {
    public:
    	stack<int> input;
    	stack<int> output;
        // Push element x to the back of queue.
        void push(int x) {
            input.push(x);
        }
    
        // Removes the element from in front of queue.
        void pop(void) {
            if(output.empty()){
            	while(!input.empty()){
    	        	output.push(input.top());
    	        	input.pop();
    	        }
            }
            output.pop();
        }
        // Get the front element.
        int peek(void) {
            if(output.empty()){
            	while(!input.empty()){
    	        	output.push(input.top());
    	        	input.pop();
    	        }
            }
            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.