The stack is a linear data structure which works on the LIFO concept. LIFO stands for last in first out. In the stack, the insertion and deletion are possible at one end the end is called the top of the stack.
In this article, we will see how to reverse a stack using Python.
- Define some basic function of the stack like push(), pop(), show(), empty(), for basic operation like respectively append an item in stack, remove an item in stack, display the stack, check the given stack is empty or not.
- Define two recursive functions BottomInsertion() and Reverse()..
BottomInsertion() : this method append element at the bottom of the stack and BottomInsertion accept two values as an argument first is stack and the second is elements, this is a recursive method.
# insert element at the bottom of the stack def BottomInsert(s, value): # if stack is empty then call push() method. if s.empty(): s.push(value) # if stack is not empty then execute else # block else: # remove the element and store it to # popped popped = s.pop() # invoke it self and pass stack and value # as an argument. BottomInsert(s, value) # append popped item in the bottom of the stack s.push(popped)
Reverse() : the method is reverse elements of the stack, this method accept stack as an argument Reverse() is also a Recursive() function. Reverse() is invoked BottomInsertion() method for completing the reverse operation on the stack.
# Reverse() def Reverse(s): # check the stack is empty of not if s.empty(): # if empty then do nothing pass # if stack is not empty then else: # pop element and stare it to popped popped = s.pop() # call it self ans pass stack as an argument Reverse(s) # call BottomInsert() method and pass stack # and popped element as an argument BottomInsert(s, popped)
Below is the implementation.
Orginal Stack 5 4 3 2 1 Stack after Reversing 1 2 3 4 5
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.