This post will implement a queue using the stack data structure in C++, Java, and Python. In other words, design a queue that supports enqueue and dequeue operations using standard push and pop operations of the stack.

We know that queue is a First–In, First–Out (FIFO) data structure in which elements are removed in the same order in which they were added to the queue. In an enqueue operation, items are added to the rear of the queue, while in dequeue operation, items are removed from the front of the queue.

There are several ways to implement a queue using one or two stacks by tweaking their push and pop operations.

1. Using two stacks

The idea is to implement the queue’s enqueue operation so that the first entered element always ends up at the top of the stack. To achieve this, we need an additional stack.

  1. To enqueue an item into the queue, first move all elements from the first stack to the second stack, push the item into the first stack, and finally move all elements back to the first stack. This ensures that the new item lies at the bottom of the stack and hence would be the last one to be removed.
  2. To dequeue an item from the queue, return the top item from the first stack.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Note that the elements are exchanged between the stacks twice for every enqueue operation. This can impact performance if enqueue operations are frequent. Here’s an alternative approach that affects the dequeue operation’s time complexity instead of the enqueue operation.

  1. To enqueue an item into the queue, push the item into the first stack.
  2. To dequeue an item from the queue, move elements from the first stack to the second stack if it is empty, and return the top item from the second stack.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

2. Using one stack with call stack

We can also use an implicit stack (call stack) and an actual stack for constructing a queue. The dequeue operation pops all elements from the stack and stores them in the call stack. When the stack is left with a single item, remove and return that item. Finally, push all elements back into the stack from the call stack as the recursion unfolds.

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code