JAVA Using two stacks 99.87% Clean code


  • 1
    Z
    class MyQueue {
    	
    	/* 91ms 99.87%
    		Only move elements of new stack to oldStack when it is needed (pop or peek and oldStack is empty)
    	*/
        Deque<Integer> newStack = new ArrayDeque<>();
        Deque<Integer> oldStack = new ArrayDeque<>();
        // Push element x to the back of queue.
        public void push(int x) {
            newStack.push(x);
        }
    
        // Removes the element from in front of queue.
        public void pop() {
            if(oldStack.isEmpty()) moveToOld();
            oldStack.pop();
        }
    
        // Get the front element.
        public int peek() {
            if(oldStack.isEmpty()) moveToOld();
            return oldStack.peek();
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            return newStack.isEmpty() && oldStack.isEmpty();
        }
        private void moveToOld() {
            while(!newStack.isEmpty()) oldStack.push(newStack.pop());
        }
    }
    

Log in to reply
 

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