Implement stack using single queue in Python

In this tutorial, we shall implement a stack using a single queue in Python. As I said in my previous post, Python does not have a specified stack data structure. A queue is a Linear Data Structure that uses a FIFO (First In First Out) methodology, just like a normal queue in the real world.

We shall create a class Queue and define the methods of a queue namely, enqueue, dequeue, top, empty, and get_size inside the class Queue. Later, we create a class called Stack with the instance variable (object level variable) q which is initialized to an empty queue. The enqueue operation of the queue works similarly to that of push operation of a stack. Whereas, dequeue removes the oldest entered element but pop in stack removes the latest entered element. So, we shall dequeue the queue and enqueue the same element to the queue. Repeating this process results in our required pop element to move towards the front of the queue. If it reaches the front of the queue, we dequeue it and return it as the popped element. top() displays the recently added element of the stack but doesn’t pop it.

>>>s.push(2)
>>>s.push(3)
>>>s.pop()
3 is popped
>>>s.push(4)
>>>s.top()
4 is top element of stack
>>>s.empty()
False
>>>s.size()
2 is size of stack

Below is the Python code to implement stack using the single queue:

class Stack:
    def __init__(self):
        self.q = Queue()
 
    def empty(self):
        print(self.q.empty())
 
    def push(self, data):
        self.q.enqueue(data)
        print(data, "is pushed")
 
    def pop(self):
        for _ in range(self.q.get_size() - 1): 
            dequeued = self.q.dequeue()  #dequeuing 
            self.q.enqueue(dequeued)     #again enqueueing it so that last element reaches front of queue
        print("{} is popped".format(self.q.dequeue())) #Dequeueing now removes the recently added element
    
    def size(self):
        print("{} is the size of stack".format(self.q.get_size()))
    
    def top(self):
        if not self.q.empty():
            print("{} is top element of stack".format(self.q.top()))
        else:
            print("Stack Empty!!!")
 
 
class Queue:
    def __init__(self):
        self.items = []
        self.size = 0

    def top(self):
        return(self.items[-1])
 
    def empty(self):
        return (self.items == [])
 
    def enqueue(self, data):
        self.size += 1
        self.items.append(data) 
    def dequeue(self):
        self.size -= 1
        return self.items.pop(0)
 
    def get_size(self):
        return self.size
 
 
s = Stack()

s.push(2)
s.push(3)
s.push(4)
s.push(5)
s.push(6)

s.pop()
s.pop()

s.empty()

s.size()

s.top()

Output:

2 is pushed
3 is pushed
4 is pushed
5 is pushed
6 is pushed
6 is popped
5 is popped
False
3 is the size of stack
4 is top element of stack

I am Vamsi Krishna and you can find my other posts here:

Also Read: Reverse a Queue in Python

Thank You for reading and Keep Learning 🙂

Leave a Reply