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

A stack is a Last–In, First–Out (LIFO) data structure in which elements are inserted and removed from one end of the stack known as the top of the stack. It has two major operations: The push operation, which adds an element into the stack, and the pop operation, which removes the most recently added element from the stack, but not yet removed.

There are several ways to implement a stack using one or two queues by tweaking their enqueue and dequeue operations.

1. Using Two Queues

The idea is to implement the queue’s enqueue operation such that the last entered item always ends up at the queue’s front. To achieve this, we need an additional queue.

  1. To push an item into the stack, first move all elements from the first queue to the second queue, then enqueue the new item into the first queue, and finally move all elements back to the first queue. This ensures that the new item lies in front of the queue and hence would be the first one to be removed.
  2. To pop an item from the stack, return the front item from the first queue.

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

C++


Download  Run Code

Output:

5
4
3
2
1
Underflow!!

Java


Download  Run Code

Output:

5
4
3
2
1
Underflow!!

Python


Download  Run Code

Output:

5
4
3
2
1
Underflow!!

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

  1. To push an item into the stack, enqueue the item to the first queue.
  2. To pop an item from the stack, move all elements from the first queue to the second queue except the last element, and then return the last element after moving all elements back to the first queue.

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

C++


Download  Run Code

Output:

5
4
3
2
1
Stack Underflow!!

Java


Download  Run Code

Output:

5
4
3
2
1
Stack Underflow!!

Python


Download  Run Code

Output:

5
4
3
2
1
Stack Underflow!!

2. Using one queue with call stack

We can also use an implicit stack (call stack) along with a queue to construct a stack, as shown below in C++, Java, and Python:

C++


Download  Run Code

Output:

5
4
3
2
1
Underflow!!

Java


Download  Run Code

Output:

5
4
3
2
1
Underflow!!

Python


Download  Run Code

Output:

5
4
3
2
1
Underflow!!