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.
  1. class Queue:
  2.     def __init__(self):
  3.         self.items = []
  4.  
  5.     def is_empty(self):
  6.         return self.items == []
  7.  
  8.     def enqueue(self, data):
  9.         self.items.append(data)
  10.  
  11.     def dequeue(self):
  12.         if self.is_empty():
  13.             return None
  14.         return self.items.pop(0)
  15.  
  16.  
  17. class Stack:
  18.     def __init__(self):
  19.         self.queue1 = Queue()
  20.         self.queue2 = Queue()
  21.  
  22.     def is_empty(self):
  23.         return self.queue2.is_empty()
  24.  
  25.     def push(self, data):
  26.         self.queue1.enqueue(data)
  27.  
  28.         while not self.queue2.is_empty():
  29.             self.queue1.enqueue(self.queue2.dequeue())
  30.  
  31.         # swap queues
  32.         self.queue1, self.queue2 = self.queue2, self.queue1
  33.  
  34.     def pop(self):
  35.         return self.queue2.dequeue()
  36.  
  37.  
  38. # ---------------- MAIN PROGRAM ----------------
  39.  
  40. while True:
  41.     print("\n=============== Implement Stack using Two Queues ===============\n")
  42.  
  43.     s = Stack()
  44.  
  45.     print("Menu")
  46.     print("push <value>")
  47.     print("pop")
  48.     print("quit")
  49.  
  50.     while True:
  51.         do = input("What would you like to do? ").split()
  52.  
  53.         if not do:
  54.             continue
  55.  
  56.         operation = do[0].lower()
  57.  
  58.         if operation == "push":
  59.             if len(do) != 2:
  60.                 print("Usage: push <value>")
  61.                 continue
  62.             s.push(int(do[1]))
  63.             print("Pushed:", do[1])
  64.  
  65.         elif operation == "pop":
  66.             if s.is_empty():
  67.                 print("Stack is empty.")
  68.             else:
  69.                 print("Popped value:", s.pop())
  70.  
  71.         elif operation == "quit":
  72.             break
  73.  
  74.         else:
  75.             print("Invalid operation.")
  76.  
  77.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  78.     if opt == "no":
  79.         print("Exiting program...")
  80.         break
  81.     elif opt != "yes":
  82.         print("Invalid choice. Exiting program...")
  83.         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 ` onto the stack, `pop` the top value, or `quit`. After each operation, it displays appropriate messages. The program continues until the user decides to exit, handling empty stack and invalid inputs gracefully.

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

Python Tutorials