Computer Science
Write a program to reverse a string using stack.
Python Stack
8 Likes
Answer
def push(stack, item):
stack.append(item)
def pop(stack):
if stack == []:
return
return stack.pop()
def reverse(string):
n = len(string)
stack = []
for i in range(n):
push(stack, string[i])
string = ""
for i in range(n):
string += pop(stack)
return string
string = input("Enter a string: ")
print("String:", string)
reversedStr = reverse(string)
print("Reversed String:", reversedStr)
Output
Enter a string: Hello world
String: Hello world
Reversed String: dlrow olleH
Answered By
4 Likes
Related Questions
Find the output of the following code:
result = 0 numberList = [10, 20, 30] numberList.append(40) result = result + numberList.pop() result = result + numberList.pop() print("Result=", result)
Find the output of the following code:
answer = []; output = '' answer.append('T') answer.append('A') answer.append('M') ch = answer.pop() output = output + ch ch = answer.pop() output = output + ch ch = answer.pop() output = output + ch print("Result=", output)
For the following arithmetic expression:
((2 + 3) * (4 / 2)) + 2
Show step-by-step process for matching parentheses using stack data structure.
Evaluate following postfix expression while showing status of stack after each operation given A = 3, B = 5, C = 1, D = 4.
AB + C *