Reverse a String using Stack
Last Updated : 04 Apr, 2025
Improve
Try it on GfG Practice
Given a string str, the task is to reverse it using stack.
Example:
Input: s = “GeeksQuiz”
Output: ziuQskeeGInput: s = “abc”
Output: cba
Also read: Reverse a String – Complete Tutorial.
As we all know, stacks work on the principle of first in, last out. After popping all the elements and placing them back into the string, the former string would be reversed.
Follow the steps given below to reverse a string using stack.
- Create an empty stack.
- One by one push all characters of string to stack.
- One by one pop all characters from stack and put them back to string.
#include <iostream>
#include <stack>
using namespace std;
string reverse(string s) {
stack<char> st;
// Push all characters onto the stack
for (char c : s)
st.push(c);
// Pop characters to form reversed string
string res;
while (!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
int main() {
string s = "geeksforgeeks";
cout << s << endl;
cout << reverse(s) << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
void reverse(char* s) {
int n = strlen(s);
for (int i = 0; i < n / 2; i++) {
char temp = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = temp;
}
}
int main() {
char s[] = "geeksforgeeks";
printf("%s\n", s);
reverse(s);
printf("%s\n", s);
return 0;
}
import java.util.Stack;
public class GfG {
public static String reverse(String s) {
Stack<Character> stack = new Stack<>();
// Push all characters onto the stack
for (char c : s.toCharArray())
stack.push(c);
// Pop characters to form reversed string
StringBuilder res = new StringBuilder();
while (!stack.isEmpty()) {
res.append(stack.pop());
}
return res.toString();
}
public static void main(String[] args) {
String s = "geeksforgeeks";
System.out.println(s);
System.out.println(reverse(s));
}
}
def reverse(s):
# Use slicing to reverse the string
return s[::-1]
s = "geeksforgeeks"
print(s)
print(reverse(s))
using System;
using System.Collections.Generic;
class GfG {
static string Reverse(string s) {
Stack<char> stack = new Stack<char>();
// Push all characters onto the stack
foreach (char c in s)
stack.Push(c);
// Pop characters to form reversed string
char[] res = new char[s.Length];
int i = 0;
while (stack.Count > 0) {
res[i++] = stack.Pop();
}
return new string(res);
}
static void Main() {
string s = "geeksforgeeks";
Console.WriteLine(s);
Console.WriteLine(Reverse(s));
}
}
function reverse(s) {
// Convert string to array, reverse it, and join back to string
return s.split('').reverse().join('');
}
let s = "geeksforgeeks";
console.log(s);
console.log(reverse(s));
Output
geeksforgeeks skeegrofskeeg
Time Complexity: O(n) Only one traversal to push and one to pop so O(n)+O(n) = O(n).
Auxiliary Space: O(n) Due to the stack