How to Implement Stack using Two Queues in Python
In this tutorial, we will learn how to program “How to Implement a Stack Using Two Queues in Python.” The objective is to implement stack operations using two queues. This tutorial will guide you step by step through the process of implementing stack operations. By the end of this tutorial, you will have a solid understanding of how to implement these tasks effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.
This topic is straightforward and easy to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of implementing a stack using two queues. So, let’s dive into the coding process!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- class Queue:
- def __init__(self):
- self.items = []
- def is_empty(self):
- return self.items == []
- def enqueue(self, data):
- self.items.append(data)
- def dequeue(self):
- if self.is_empty():
- return None
- return self.items.pop(0)
- class Stack:
- def __init__(self):
- self.queue1 = Queue()
- self.queue2 = Queue()
- def is_empty(self):
- return self.queue2.is_empty()
- def push(self, data):
- self.queue1.enqueue(data)
- while not self.queue2.is_empty():
- self.queue1.enqueue(self.queue2.dequeue())
- # swap queues
- self.queue1, self.queue2 = self.queue2, self.queue1
- def pop(self):
- return self.queue2.dequeue()
- # ---------------- MAIN PROGRAM ----------------
- while True:
- print("\n=============== Implement Stack using Two Queues ===============\n")
- s = Stack()
- print("Menu")
- print("push <value>")
- print("pop")
- print("quit")
- while True:
- do = input("What would you like to do? ").split()
- if not do:
- continue
- operation = do[0].lower()
- if operation == "push":
- if len(do) != 2:
- print("Usage: push <value>")
- continue
- s.push(int(do[1]))
- print("Pushed:", do[1])
- elif operation == "pop":
- if s.is_empty():
- print("Stack is empty.")
- else:
- print("Popped value:", s.pop())
- elif operation == "quit":
- break
- else:
- print("Invalid operation.")
- opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
- if opt == "no":
- print("Exiting program...")
- break
- elif opt != "yes":
- print("Invalid choice. Exiting program...")
- break
This Python program demonstrates how to implement a stack using two queues. It defines a `Queue` class with standard operations (`enqueue`, `dequeue`, `is_empty`) and a `Stack` class that internally uses two queues (`queue1` and `queue2`) to emulate stack behavior (LIFO).
To push a value onto the stack, the program enqueues the new value into `queue1`, then moves all elements from `queue2` into `queue1` to maintain the correct order. After this, it swaps the two queues so that `queue2` always contains the stack in proper order for popping. To pop from the stack, the program simply dequeues from `queue2`.
The interactive main program provides a menu where the user can `push
Output:
There you have it we successfully created How to Implement Stack using Two Queues in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language