English

Write a program to reverse a string using stack. - Computer Science (Python)

Advertisements
Advertisements

Question

Write a program to reverse a string using stack.

Answer in Brief

Solution

 

Reverse a String Using Stack

def POP(stack) :
if stack ! = []:
return stack.pop()
else:
#UNDERFLOW
return

def PUSH(stack, ch):
stack.append(ch)

def ReverseString(string) :
stack = []
for ch in string:
PUSH(Stack, ch)

revstring = ''
while True:
ch = POP(stack)
if ch! = None:
revstring = revstring + ch
else :
break

return revstring

#____main____

string = input("enter a string : ")

revstring = ReverseString(string)

print("Reverse String is", revstring)
Output:

enter a string : My name is manisha kore.
Reverse String is  erok ahsinam si eman yM
shaalaa.com
  Is there an error in this question or solution?
Chapter 3: Stack - Exercise [Page 52]

APPEARS IN

NCERT Computer Science [English] Class 12
Chapter 3 Stack
Exercise | Q 3. | Page 52
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×