Today we are going to share a Python code to reverse a string using stack. If you are a python beginner and want to start learning the python programming, then keep your close attention in this tutorial as I am going to share a Python code to reverse a string using the stack.
To increase your Python knowledge, practice all Python programs, here is a collection of 100+ Python problems with solutions.
Copy the below python program and execute it with the help of python compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
def createStack(): stack=[] return stack def size(stack): return len(stack) def isEmpty(stack): if size(stack) == 0: return true def push(stack,item): stack.append(item) def pop(stack): if isEmpty(stack): return return stack.pop() def reverse(string): n = len(string) stack = createStack() # Push all characters of string to stack for i in range(0,n,1): push(stack,string[i]) string="" for i in range(0,n,1): string+=pop(stack) return string s = "Freewebmentor" print ("The original string is : ",end="") print (s) print ("The reversed string(using stack) is : ",end="") print (reverse(s)) |
The original string is : Freewebmentor
The reversed string(using stack) is : rotnembeweerf
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.