Simple Java solution using two stacks. Stack Class.


  • 0
    O
    class MyQueue {
        Stack<Integer> head, tail;
        
        public MyQueue() {
            head = new Stack<Integer>();
            tail = new Stack<Integer>();
        }
        
        // Push element x to the back of queue.
        public void push(int x) {
            tail.push(x);
        }
    
        // Removes the element from in front of queue.
        public void pop() {
            if (!head.isEmpty()) {
                head.pop();
            } else {
                while(!tail.isEmpty()) {
                    head.push(tail.pop());
                }
                head.pop();
            }
        }
    
        // Get the front element.
        public int peek() {
            if (head.isEmpty() && tail.isEmpty()) {
                return 0;
            }
            if (head.isEmpty()) {
                while(!tail.isEmpty()) {
                    head.push(tail.pop());
                }
            }
            return head.peek();
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            if (head.isEmpty() && tail.isEmpty()) {
                return true;
            }
            return false;
        }
    }
    

Log in to reply
 

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