Python Program to Implement Stack using One Queue

PythonServer Side ProgrammingProgramming

When it is required to implement a stack using a single queue, a ‘Stack_structure’ class is required along with a Queue_structure class. Respective methods are defined in these classes to add and delete values from the stack and queue respectively.

Below is a demonstration of the same −

Example

Live Demo

class Stack_structure:
def __init__(self):
self.q = Queue_structure()

def check_empty(self):
return self.q.check_empty()

def push_val(self, data):
self.q.enqueue_operation(data)

def pop_val(self):
for _ in range(self.q.size_calculate() - 1):
dequeued = self.q.dequeue_operation()
self.q.enqueue_operation(dequeued)
return self.q.dequeue_operation()

class Queue_structure:
def __init__(self):
self.items = []
self.size = 0

def check_empty(self):
return self.items == []

def enqueue_operation(self, data):
self.size += 1
self.items.append(data)

def dequeue_operation(self):
self.size -= 1
return self.items.pop(0)

def size_calculate(self):
return self.size

my_instance = Stack_structure()

print('push <value>')
print('pop')
print('quit')

while True:
my_input = input('What operation would you like to perform ? ').split()

operation = my_input[0].strip().lower()
if operation == 'push':
my_instance.push_val(int(my_input[1]))
elif operation == 'pop':
if my_instance.check_empty():
print('The stack is empty.')
else:
print('The deleted value is : ', my_instance.pop_val())
elif operation == 'quit':
break

Output

Menu
push <value>
pop
quit
What operation would you like to perform ? push 89
What operation would you like to perform ? push 43
What operation would you like to perform ? push 76
What operation would you like to perform ? push 56
What operation would you like to perform ? pop
The deleted value is : 56
What operation would you like to perform ? quit

Explanation

• A ‘Stack_structure’ class is created that initializes an empty list.

• A ‘check_empty’ method is defined to see if a stack is empty.

• Another method named ‘push_val’ is defined that adds elements to the stack.

• Another method named ‘pop_val’ is defined that deletes elements from the stack.

• A ‘Queue_structure’ class is created that initializes an empty list and assigns size of list as 0.

• A ‘check_empty’ method is defined to see if a queue is empty.

• Another method named ‘enqueue_operation’ is defined that adds elements to the queue.

• Another method named ‘dequeue_operation’ is defined that deletes elements from the queue.

• Another method named ‘size_calculate’ is defined, that determines the size of the queue.

• An instance of this ‘Stack_structure’ is defined.

• Four options are given- Menu, push, pop, and quit.

• Based on the inut given by the user, operations are performed on the elements of stack.

• The output is displayed on the console.

Published on 15-Apr-2021 12:42:38