Accepted Java Solution


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

Log in to reply
 

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