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
self.stack_1 = list()
self.stack_2 = list()
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:
element = self.stack_1.pop()
if __name__ == "__main__":
q = Queue()
The output of the program to implement queue using stack is as follows:
PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
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.
program by tutorialsinhand.com
About the Author
Full Stack Web Developer & Blockchain Enthusiast
Page Views :
Published Date :