Share My Java Solution.


  • 1
    Z
        class MyQueue {
        Stack<Integer> in = new Stack<>();
        Stack<Integer> out = new Stack<>();
        // Push element x to the back of queue.
        public void push(int x) {
            in.push(x);
        }
    
        // Removes the element from in front of queue.
        public void pop() {
            if(out.isEmpty()){
                queueing();
            }
            if(out.isEmpty())
                return;
            
            out.pop();
        }
    
        // Get the front element.
        public int peek() {
            if(out.isEmpty()){
                queueing();
            }
            return out.peek();
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            return in.isEmpty() && out.isEmpty();
        }
        
        private void queueing(){
            if(out.isEmpty()){
               while(!in.isEmpty()){
                   out.push(in.pop());
               } 
            }
        }
        
    }
    

    The only time you need to push data from in stack to out stack is when the out stack is empty. No need to pull everything from in stack every time and push them back once the pop or peek is done.


Log in to reply
 

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