Stack to reverse string using python

Reverse String with help of stack

This Program is accepting string from user and with help of stack it will display the reverse of the string.

This program will help students to understand the concepts of stack and its working. This program is best for beginner as a starter.

Working of program.

  • Accept string from the user.
  • Scan complete string from left to right.
  • Push each element/character in stack.
  • Once scanning is done.
  • Start popping element from stack and append it to result list.
  • Once the stack is empty return the result in string form.
  • Display the result

There is only one end in stack from which element can be inserted/push or removed/pop. This feature helps in smooth execution of this program.

class  Stack_to_reverse  :
    # Creates  an  empty  stack.
    def	__init__(  self  ):
        self.items  =  list()
        self.size=-1
#Author : ITVoyagers Website : itvoyagers.in
    #Returns  True  if  the  stack  is  empty  or  False  otherwise.
    def  isEmpty(  self  ):
        if(self.size==-1):
            return True
        else:
            return False
#Author : ITVoyagers Website : itvoyagers.in
    # Removes  and  returns  the  top  item  on  the  stack.
    def  pop(  self  ):
        if  self.isEmpty():
            print("Stack is empty")
        else:
            return self.items.pop()
            self.size-=1

    # Push  an  item  onto  the  top  of  the  stack.
    def  push(  self,  item  ):
        self.items.append(item)
        self.size+=1

    def reverse(self,string):
        n = len(string)
#Author : ITVoyagers Website : itvoyagers.in
 # Push all characters of string to stack
        for i in range(0,n):
            S.push(string[i])

 # Making the string empty since all characters are saved in stack
        string=""

 # Pop all characters of string and put them back to string
#Author : ITVoyagers Website : itvoyagers.in
        for i in range(0,n):
            string+=S.pop()
        return string

S=Stack_to_reverse()
seq=input("Enter a string to be reversedn")
sequence = S.reverse(seq)
print("Reversed string is " + sequence)
#Author : ITVoyagers Website : itvoyagers.in

Output:

Enter a string to be reversed
ITVOYAGERS
Reversed string is SREGAYOVTI

Note : Please note that above program is compatible with Python 3 or higher version.

You can also check following content on conversion, evaluation and other applications of stack

1 thought on “Stack to reverse string using python”

Leave a Comment