Reversing a string using a stack means pushing all characters onto the stack and then popping them one by one. Since a stack follows the Last In, First Out (LIFO) principle, the characters are retrieved in reverse order.
- Push each character of the string onto the stack.
- Pop the characters and place them back into the string to obtain the reversed string.
Examples:
Input: GeeksQuiz
Output: ziuQskeeGInput: HelloWorld
Output: HelloWorld
Approach
The approach follows these steps:
- Create an empty stack.
- Push each character of the string onto the stack.
- Pop each character from the stack.
- Store the popped characters back into the string.
- The resulting string is the reverse of the original string.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
void reverseString(string& str)
{
stack<char> st;
// Push all characters onto the stack
for (char ch : str)
st.push(ch);
// Pop characters and store them back
for (char& ch : str) {
ch = st.top();
st.pop();
}
}
int main()
{
string str = "GeeksQuiz";
reverseString(str);
cout << "Reversed string is " << str;
return 0;
}
Output
Reversed string is ziuQskeeG
Explanation: The string "GeeksQuiz" is pushed into the stack from left to right. The last character, 'z', is pushed last and therefore popped first. Similarly, the remaining characters are popped in reverse order and placed back into the string.
Thus, the original string:
G e e k s Q u i z
becomes:
z i u Q s k e e G
and the final result is:
ziuQskeeG