Python Program to Implement Stack Using Two Queues

A stack follows Last-In-First-Out (LIFO) principle, while a queue follows First-In-First-Out (FIFO). This tutorial shows how to implement a stack using two queues, demonstrating an interesting data structure transformation.

Stack and Queue Classes

We need two classes: one for queue operations and another for stack implementation using two queues ?

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

class Stack_structure:
    def __init__(self):
        self.queue_1 = Queue_structure()
        self.queue_2 = Queue_structure()
    
    def check_empty(self):
        return self.queue_2.check_empty()
    
    def push_val(self, data):
        self.queue_1.enqueue_operation(data)
        while not self.queue_2.check_empty():
            x = self.queue_2.dequeue_operation()
            self.queue_1.enqueue_operation(x)
        self.queue_1, self.queue_2 = self.queue_2, self.queue_1
    
    def pop_val(self):
        return self.queue_2.dequeue_operation()

# Example usage
stack = Stack_structure()

# Push elements
stack.push_val(10)
stack.push_val(20)
stack.push_val(30)

# Pop elements
print(f"Popped: {stack.pop_val()}")
print(f"Popped: {stack.pop_val()}")
print(f"Popped: {stack.pop_val()}")
Popped: 30
Popped: 20
Popped: 10

How It Works

The algorithm maintains two queues and swaps their roles:

  • Push Operation: Add new element to queue_1, transfer all elements from queue_2 to queue_1, then swap the queues
  • Pop Operation: Simply dequeue from queue_2 (which contains elements in LIFO order)
  • Queue Swapping: Ensures the most recent element is always at the front of the active queue

Interactive Stack Operations

Here's a complete program with user interaction ?

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

class Stack_structure:
    def __init__(self):
        self.queue_1 = Queue_structure()
        self.queue_2 = Queue_structure()
    
    def check_empty(self):
        return self.queue_2.check_empty()
    
    def push_val(self, data):
        self.queue_1.enqueue_operation(data)
        while not self.queue_2.check_empty():
            x = self.queue_2.dequeue_operation()
            self.queue_1.enqueue_operation(x)
        self.queue_1, self.queue_2 = self.queue_2, self.queue_1
    
    def pop_val(self):
        return self.queue_2.dequeue_operation()

my_instance = Stack_structure()

print('Menu')
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('Stack is empty.')
        else:
            print('The deleted value is:', my_instance.pop_val())
    elif operation == 'quit':
        break

Sample Output

Menu
push <value>
pop
quit
What operation would you like to perform ? push 56
What operation would you like to perform ? push 34
What operation would you like to perform ? push 78
What operation would you like to perform ? push 90
What operation would you like to perform ? pop
The deleted value is: 90
What operation would you like to perform ? quit

Time Complexity

Operation Time Complexity Reason
Push O(n) Transfer all elements between queues
Pop O(1) Simple dequeue operation
Check Empty O(1) Check queue status

Conclusion

Implementing a stack using two queues demonstrates queue manipulation techniques. While push operations are O(n), this approach showcases how different data structures can simulate each other's behavior through creative algorithms.

Updated on: 2026-03-25T18:41:53+05:30

636 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements