Sitemap

Reversing a string using a Stack | Python

Problem:

1 min readApr 8, 2023

--

Given a string, write a Python function that uses a Stack to reverse the string.

Press enter or click to view image in full size
Photo by Clint Patterson on Unsplash

Solution:

To reverse a string using a Stack, we need to push each character of the string onto the stack and then pop them off in reverse order. The first step is to create an empty Stack. Then, we iterate through the string, pushing each character onto the Stack. Once we’ve pushed all the characters, we pop them off one by one and append them to a new string to create the reversed string.

def reverse_string(s):
stack = []
reversed_string = ""

# push each character of the string onto the stack
for char in s:
stack.append(char)

# pop each character from the stack and append to reversed_string
while len(stack) != 0:
reversed_string += stack.pop()

return reversed_string

This function takes a string s as input, initializes an empty stack, pushes each character of the string onto the stack, and then pops each character from the stack and appends it to a new string reversed_string. Finally, the reversed string is returned.

Get Saurabh Mishra’s stories in your inbox

Join Medium for free to get updates from this writer.

Here’s an example of how you could use this function:

string_to_reverse = "hello world"
reversed_string = reverse_string(string_to_reverse)
print(reversed_string) # should print "dlrow olleh"

--

--

Saurabh Mishra
Saurabh Mishra

Written by Saurabh Mishra

Full Stack Developer || Founder@LearnNGrowIt