Queues: A Tale of Two Stacks

  • + 19 comments

    I went down the wrong path at first: transferring data between stacks for every operation. Then I realized that in theory, we never needed to transfer from the 'old' stack to the 'new' stack.

            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());
            }