Reverse a string using stack data structure

In this post, we will discuss how to reverse a string using stack data structure.


 

1. Using explicit stack

The idea is to create an empty stack and push all character of the string to it. The we pop each character one by one from the stack and put them back to the input string starting from the 0’th index.

C++

Download   Run Code

Output:

em esreveR

Java

Download   Run Code

Output:

em esreveR

 

2. Using implicit stack

We can also use implicit stack i.e. recursive call stack to reverse a string as shown below:

C

Download   Run Code

Output:

em esreveR

C++

Download   Run Code

Output:

em esreveR

 
Here’s alternative easier approach which also takes advantage of the implicit stack to reverse the string.

C

Download   Run Code

Output:

em esreveR

C++

Download   Run Code

Output:

em esreveR

Java

Download   Run Code

Output:

em esreveR

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of