Python Program to Reverse a Stack using Recursion


When it is required to reverse a stack data structure using recursion, a ‘stack_reverse’ method, in addition to methods to add value, delete value, and print the elements of the stack are defined.

Below is a demonstration of the same −

Example

 Live Demo

class Stack_structure:
   def __init__(self):
      self.items = []

   def check_empty(self):
      return self.items == []

   def push_val(self, data):
      self.items.append(data)

   def pop_val(self):
      return self.items.pop()

   def print_it(self):
      for data in reversed(self.items):
         print(data)

def insert_bottom(instance, data):
   if instance.check_empty():
      instance.push_val(data)
   else:
      deleted_elem = instance.pop_val()
      insert_bottom(instance, data)
      instance.push_val(deleted_elem)

def stack_reverse(instance):
   if not instance.check_empty():
      deleted_elem = instance.pop_val()
      stack_reverse(instance)
      insert_bottom(instance, deleted_elem)

my_instance = Stack_structure()
data_list = input('Enter the elements to add to the stack: ').split()
for data in data_list:
   my_instance.push_val(int(data))

print('The reversed stack is:')
my_instance.print_it()
stack_reverse(my_instance)
print('The stack is:')
my_instance.print_it()

Output

Enter the elements to add to the stack: 23 56 73 81 8 9 0
The reversed stack is:
0
9
8
81
73
56
23
The stack is:
23
56
73
81
8
9
0

Explanation

  • A ‘Stack_structure’ class is created that initializes an empty list.

  • A ‘check_empty’ method is defined to see if a stack is empty.

  • Another method named ‘push_val’ is defined that adds elements to the stack.

  • Another method named ‘pop_val’ is defined that deletes elements from the stack.

  • A method named ‘print_it’ is defined that helps print the elements of the stack.

  • A method named ‘insert_bottom’ is defined, that adds element to the bottom of the stack, instead of adding to the top by default.

  • Another method named ‘stack_reverse’ is defined, that helps reverse a given stack.

  • An instance of this ‘Stack_structure’ is defined.

  • The elements of stack are taken from the user.

  • It is iterated over, and methods are called to add value to the stack and print it on the console.

  • Now, the ‘stack_reverse’ is called on this list.

  • The ‘print_it’ is called to display the reversed stack on the console.

Updated on: 15-Apr-2021

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements