Sharing My Java Solution (Beats 65%)


  • 0
    G
    class MyQueue {
        // Push element x to the back of queue.
        Stack<Integer> curStack = new Stack<>();
        Stack<Integer> tempStack = new Stack<>();
        
        public void push(int x) {
            curStack.push(x);
        }
    
        // Removes the element from in front of queue.
        public void pop() {
            while(curStack.size()>0){
                tempStack.push(curStack.pop());
            }
            tempStack.pop();
            while(tempStack.size()>0){
                curStack.push(tempStack.pop());
            }
        }
    
        // Get the front element.
        public int peek() {
            while(curStack.size()>0){
                tempStack.push(curStack.pop());
            }
            int peek = tempStack.peek();
            while(tempStack.size()>0){
                curStack.push(tempStack.pop());
            }
            return peek;
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            return curStack.size()==0;
        }
    }
    

Log in to reply
 

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