Open In App

Python program to reverse a stack

Last Updated : 18 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.
 

Algorithm: 

 

  • 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.

 

Python3




# create class for stack
class Stack:
 
    # create empty list
    def __init__(self):
        self.Elements = []
         
    # push() for insert an element
    def push(self, value):
        self.Elements.append(value)
       
    # pop() for remove an element
    def pop(self):
        return self.Elements.pop()
     
    # empty() check the stack is empty of not
    def empty(self):
        return self.Elements == []
     
    # show() display stack
    def show(self):
        for value in reversed(self.Elements):
            print(value)
 
# Insert_Bottom() insert value at bottom
def BottomInsert(s, value):
   
    # check the stack is empty or not
    if s.empty():
         
        # if stack is empty then call
        # push() method.
        s.push(value)
         
    # if stack is not empty then execute
    # else block
    else:
        popped = s.pop()
        BottomInsert(s, value)
        s.push(popped)
 
# Reverse() reverse the stack
def Reverse(s):
    if s.empty():
        pass
    else:
        popped = s.pop()
        Reverse(s)
        BottomInsert(s, popped)
 
 
# create object of stack class
stk = Stack()
 
stk.push(1)
stk.push(2)
stk.push(3)
stk.push(4)
stk.push(5)
 
print("Original Stack")
stk.show()
 
print("\nStack after Reversing")
Reverse(stk)
stk.show()


Output:

Original Stack
5
4
3
2
1

Stack after Reversing
1
2
3
4
5

Time complexity: O(n) where n is the size of given stack

Auxiliary space: O(n)



Previous Article
Next Article

Similar Reads

Python Program to Reverse the Content of a File using Stack
Given a file, the task is to change the content in reverse order using Stack, as well as store the lines of that file in reverse order in Python. Examples: Input: 1 2 3 4 5 Output: 5 4 3 2 1 Approach to Python Program to Reverse a Stack Using Recursion Create an empty stack. One by one push every line of the file to the stack. One by one pop each l
2 min read
Program to reverse a linked list using Stack
Given a linked list. The task is to reverse the order of the elements of the Linked List using an auxiliary Stack. Examples: Input : List = 3 -> 2 -> 1 Output : 1 -> 2 -> 3 Input : 9 -> 7 -> 4 -> 2 Output : 2 -> 4 -> 7 -> 9 Algorithm: Traverse the list and push all of its nodes onto a stack.Traverse the list from the h
7 min read
Java Program to Reverse a String using Stack
The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first. Approach: Push the character one by one into the Stack of datatype character.Pop the character one by one from the Stack until the stack becomes empty.Add a popped element to the character
2 min read
C Program to Reverse a Stack using Recursion
Write a program to reverse a stack using recursion, without using any loop. Example:  Input: elements present in stack from top to bottom 1 2 3 4 Output: 4 3 2 1  Input: elements present in stack from top to bottom 1 2 3Output: 3 2 1 Recommended PracticeReverse a StackTry It!Reverse a stack using Recursion The idea of the solution is to hold all va
5 min read
C++ Program to Reverse a String Using Stack
Given a string, reverse it using stack. For example "GeeksQuiz" should be converted to "ziuQskeeG". Following is simple algorithm to reverse a string using stack. 1) Create an empty stack.2) One by one push all characters of string to stack.3) One by one pop all characters from stack and put them back to string.Recommended PracticeReverse a string
4 min read
Find maximum in stack in O(1) without using additional stack in Python
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack in Python. Examples: Input: Consider the following SpecialStack 16 –> TOP29151918When getMax() is called it should return 29, which is the maximum element in the current stack. If we do pop two times on stack, the stack becom
3 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Print Reverse a linked list using Stack
Given a linked list, print the reverse of it without modifying the list. Examples: Input : 1 2 3 4 5 6 Output : 6 5 4 3 2 1 Input : 12 23 34 45 56 67 78 Output : 78 67 56 45 34 23 12 Below are different solutions that are now allowed here as we cannot use extra space and modify the list. Recursive solution to print reverse a linked list. Requires e
9 min read
Reverse alternate levels of a perfect binary tree using Stack
Given a Perfect Binary Tree, the task is to reverse the alternate level nodes of the binary tree.Examples: Input: a / \ b c / \ / \ d e f g / \ / \ / \ / \ h i j k l m n o Output: Inorder Traversal of given tree h d i b j e k a l f m c n g o Inorder Traversal of modified tree o d n c m e l a k f j b i g h Input: a / \ b c Output: Inorder Traversal
10 min read
Reverse the Words of a String using Stack
Given string str consisting of multiple words, the task is to reverse the entire string word by word.Examples: Input: str = "I Love To Code" Output: Code To Love IInput: str = "data structures and algorithms" Output: algorithms and structures data Approach: This problem can be solved not only with the help of the strtok() but also it can be solved
8 min read
three90RightbarBannerImg