Write a program to reverse a string using stack.
Program to reverse a string using stack
def reverse_string_using_stack(string): # Create an empty stack using list stack = []
# Push all characters of string to stack using append()
for char in string:
stack.append(char)
# Pop all characters from stack to get reversed string
reversed_string = ""
while len(stack) != 0:
reversed_string = reversed_string + stack.pop()
return reversed_string
Main program
string = input("Enter a string: ") reversed_str = reverse_string_using_stack(string) print("Original string:", string) print("Reversed string:", reversed_str)
Explanation
The textbook explains that stack is a linear data structure implemented using Python list with append() and pop() methods. To reverse a string, characters are pushed onto the stack one by one. When popped, they come out in reverse order due to LIFO (Last In First Out) property. The program creates an empty list as stack, pushes each character using append(), then pops characters using pop() to build the reversed string. This demonstrates the practical application of stack in string reversal as mentioned in section 3.2.1.
Solution Steps
Step 1: Create an empty stack using list
Step 2: Traverse the string and push each character onto stack using append()
Step 3: Pop characters from stack one by one using pop() and concatenate them
Step 4: The popped characters form the reversed string due to LIFO property