Last Updated : 04 Apr, 2025
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.
#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;
}
C
#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;
}
Java
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));
}
}
Python
def reverse(s):
# Use slicing to reverse the string
return s[::-1]
s = "geeksforgeeks"
print(s)
print(reverse(s))
C#
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));
}
}
JavaScript
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));
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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4