This post will discuss how to reverse a string using the stack data structure in C/C++, Java, and Python.

1. Using explicit stack

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

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

em esreveR

Java


Download  Run Code

Output:

em esreveR

Python


Download  Run Code

Output:

em esreveR

The time complexity of the above solution is O(n), where n is the length of the input string. The auxiliary space required by the program is O(n) for the stack data structure.

2. Using implicit stack

We can also use an implicit stack, i.e., call stack., to reverse a string, as demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

em esreveR

C++


Download  Run Code

Output:

em esreveR

Python


Download  Run Code

Output:

em esreveR

Here’s the alternative, more straightforward approach that 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

Python


Download  Run Code

Output:

em esreveR

The time complexity of the above solution is O(n), where n is the length of the input string. The auxiliary space required by the program is O(n) for recursion (call stack).