Stack & Queues - Queues: A Tale of Two Stacks [M]

 In this challenge, you must first implement a queue using two stacks. Then process  queries, where each query is one of the following  types:

  1. 1 x: Enqueue element  into the end of the queue.
  2. 2: Dequeue the element at the front of the queue.
  3. 3: Print the element at the front of the queue.

Sample Input
10
1 42
2
1 14
3
1 28
3
1 60
1 78
2
2

Sample Output
14
14

Explanation

image

 public static class MyQueue<T> {
        Stack<T> stackNewestOnTop = new Stack<T>();
        Stack<T> stackOldestOnTop = new Stack<T>();

        public void enqueue(T value) { // Push onto newest stack
            stackNewestOnTop.push(value);
        }

        public T peek() {
              prepOld();
             return stackOldestOnTop.peek();
        }

        public T dequeue() {
            prepOld();
            return stackOldestOnTop.pop();
        }
        
        public void prepOld(){
            if (stackOldestOnTop.isEmpty())
                while(!stackNewestOnTop.isEmpty())
                    stackOldestOnTop.push(stackNewestOnTop.pop());
        }
    }

留言

這個網誌中的熱門文章

考績被打差了 輕率離職會更傷

Arrays - DS (Reverse array) [Easy]

WireMock