Implement a queue using 2 stacks

Implement a queue using 2 stacks. Specifically, implement the enqueue and dequeue methods.

Image result for stack rifle bullets

Approach

In the constructor initialize 2 stacks, “inbox” and “outbox”. The enqueue method pushes the value  onto inbox.

The dequeue method pops from outbox if it’s not empty, otherwise pop all items from  inbox onto outbox. If they’re both empty throw an exception

Solution

public class Queue<E>
{

private Stack<E> inbox = new Stack<E>();
private Stack<E> outbox = new Stack<E>();

public void queue(E item) {
inbox.push(item);
}

public E dequeue() {
if (outbox.isEmpty()) {
while (!inbox.isEmpty()) {
outbox.push(inbox.pop());
}
}
return outbox.pop();
}

}

Comments

Post a Comment