Program to implement queue using Stack in Python
In the given python programming article, we are going to learn
-
program to implement queue using stack in python
Program to implement Queue using Stack in Python
The program to implement queue using stack in python is as follows:
# Owner : TutorialsInhand Author : Devjeet Roy
class Queue:
def __init__(self):
self.stack_1 = list()
self.stack_2 = list()
def enqueue(self,item):
self.stack_1.append(item)
def dequeue(self):
if len(self.stack_1) == 0 and len(self.stack_2) == 0:
print("The Queue is empty.")
elif len(self.stack_1) > 0 and len(self.stack_2) == 0:
while(len(self.stack_1)):
element = self.stack_1.pop()
self.stack_2.append(element)
print(self.stack_2.pop())
else:
print(self.stack_2.pop())
if __name__ == "__main__":
q = Queue()
q.enqueue("Apple")
q.enqueue("Mango")
q.enqueue("Banana")
q.dequeue()
q.dequeue()
q.dequeue()
The output of the program to implement queue using stack is as follows:
PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Apple
Mango
Banana
Few important tips about the program
1. The enqueue() operation is just about pushing the item into the first stack.
2. In case of the dequeue() method, first elements from the first stack is popped and pushed into the second stack and then removed from the second stack based on LIFO. If the first stack is empty, that means all elements from first stack has already been pushed into the second stack. So just the top of the second stack is removed.
3. The enqueue() has time complexity of O(1) and the dequeue() has that of O(n).
Program to implement queue using stack snapshot:
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Devjeet Roy
Full Stack Web Developer & Blockchain Enthusiast
Page Views :
Published Date :
Apr 14,2021