C++ Program to Reverse a String Using Stack

Last Updated : 22 Aug, 2026

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: ziuQskeeG

Input: HelloWorld
Output: HelloWorld

Approach

The approach follows these steps:

  1. Create an empty stack.
  2. Push each character of the string onto the stack.
  3. Pop each character from the stack.
  4. Store the popped characters back into the string.
  5. The resulting string is the reverse of the original string.
C++
#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

Try It Yourself
redirect icon
Comment