Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to Reverse a Stack using Recursion
A stack is a Last-In-First-Out (LIFO) data structure. To reverse a stack using recursion, we need two key functions: one to reverse the stack and another to insert elements at the bottom of the stack.
Stack Implementation
First, let's create a stack class with basic operations ?
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, data):
self.items.append(data)
def pop(self):
if not self.is_empty():
return self.items.pop()
def display(self):
print("Stack (top to bottom):", end=" ")
for item in reversed(self.items):
print(item, end=" ")
print()
Recursive Functions for Stack Reversal
The reversal requires two recursive functions ?
def insert_at_bottom(stack, item):
"""Insert item at the bottom of stack using recursion"""
if stack.is_empty():
stack.push(item)
else:
# Remove top element
temp = stack.pop()
# Recursively insert at bottom
insert_at_bottom(stack, item)
# Push back the removed element
stack.push(temp)
def reverse_stack(stack):
"""Reverse the stack using recursion"""
if not stack.is_empty():
# Remove top element
temp = stack.pop()
# Recursively reverse remaining stack
reverse_stack(stack)
# Insert removed element at bottom
insert_at_bottom(stack, temp)
Complete Example
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, data):
self.items.append(data)
def pop(self):
if not self.is_empty():
return self.items.pop()
def display(self):
print("Stack (top to bottom):", end=" ")
for item in reversed(self.items):
print(item, end=" ")
print()
def insert_at_bottom(stack, item):
"""Insert item at the bottom of stack using recursion"""
if stack.is_empty():
stack.push(item)
else:
temp = stack.pop()
insert_at_bottom(stack, item)
stack.push(temp)
def reverse_stack(stack):
"""Reverse the stack using recursion"""
if not stack.is_empty():
temp = stack.pop()
reverse_stack(stack)
insert_at_bottom(stack, temp)
# Create stack and add elements
my_stack = Stack()
elements = [10, 20, 30, 40, 50]
for element in elements:
my_stack.push(element)
print("Original Stack:")
my_stack.display()
# Reverse the stack
reverse_stack(my_stack)
print("Reversed Stack:")
my_stack.display()
Original Stack: Stack (top to bottom): 50 40 30 20 10 Reversed Stack: Stack (top to bottom): 10 20 30 40 50
How It Works
The algorithm works in two phases:
-
Recursive Removal:
reverse_stack()removes elements one by one from top to bottom -
Bottom Insertion:
insert_at_bottom()places each removed element at the bottom of the remaining stack
This effectively reverses the order of all elements in the stack.
Time and Space Complexity
| Aspect | Complexity | Reason |
|---|---|---|
| Time | O(n²) | Each element requires O(n) operations to insert at bottom |
| Space | O(n) | Recursive call stack depth |
Conclusion
Reversing a stack using recursion involves two recursive functions: one to reverse and another to insert at bottom. While elegant, this approach has O(n²) time complexity due to the bottom insertion process.
Advertisements
