How to Reverse a String using Stack
Last Updated :
23 Mar, 2023
Given a string, reverse it using stack.
Example:
Input: str = “GeeksQuiz”
Output: ziuQskeeG
Input: str = “abc”
Output: cba
Approach:
The idea is to create an empty stack and push all the characters from the string into it. Then pop each character one by one from the stack and put them back into the input string starting from the 0’th index. As we all know, stacks work on the principle of first in, last out. After popping all the elements and placing them back to string, the formed 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.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
class Stack {
public :
int top;
unsigned capacity;
char * array;
};
Stack* createStack(unsigned capacity)
{
Stack* stack = new Stack();
stack->capacity = capacity;
stack->top = -1;
stack->array
= new char [(stack->capacity * sizeof ( char ))];
return stack;
}
int isFull(Stack* stack)
{
return stack->top == stack->capacity - 1;
}
int isEmpty(Stack* stack) { return stack->top == -1; }
void push(Stack* stack, char item)
{
if (isFull(stack))
return ;
stack->array[++stack->top] = item;
}
char pop(Stack* stack)
{
if (isEmpty(stack))
return -1;
return stack->array[stack->top--];
}
void reverse( char str[])
{
int n = strlen (str);
Stack* stack = createStack(n);
int i;
for (i = 0; i < n; i++)
push(stack, str[i]);
for (i = 0; i < n; i++)
str[i] = pop(stack);
}
int main()
{
char str[] = "GeeksQuiz" ;
reverse(str);
cout << "Reversed string is " << str;
return 0;
}
|
C
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Stack {
int top;
unsigned capacity;
char * array;
};
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack
= ( struct Stack*) malloc ( sizeof ( struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array
= ( char *) malloc (stack->capacity * sizeof ( char ));
return stack;
}
int isFull( struct Stack* stack)
{
return stack->top == stack->capacity - 1;
}
int isEmpty( struct Stack* stack)
{
return stack->top == -1;
}
void push( struct Stack* stack, char item)
{
if (isFull(stack))
return ;
stack->array[++stack->top] = item;
}
char pop( struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}
void reverse( char str[])
{
int n = strlen (str);
struct Stack* stack = createStack(n);
int i;
for (i = 0; i < n; i++)
push(stack, str[i]);
for (i = 0; i < n; i++)
str[i] = pop(stack);
}
int main()
{
char str[] = "GeeksQuiz" ;
reverse(str);
printf ( "Reversed string is %s" , str);
return 0;
}
|
Java
import java.util.*;
class Stack {
int size;
int top;
char [] a;
boolean isEmpty() { return (top < 0 ); }
Stack( int n)
{
top = - 1 ;
size = n;
a = new char [size];
}
boolean push( char x)
{
if (top >= size) {
System.out.println( "Stack Overflow" );
return false ;
}
else {
a[++top] = x;
return true ;
}
}
char pop()
{
if (top < 0 ) {
System.out.println( "Stack Underflow" );
return 0 ;
}
else {
char x = a[top--];
return x;
}
}
}
class Main {
public static void reverse(StringBuffer str)
{
int n = str.length();
Stack obj = new Stack(n);
int i;
for (i = 0 ; i < n; i++)
obj.push(str.charAt(i));
for (i = 0 ; i < n; i++) {
char ch = obj.pop();
str.setCharAt(i, ch);
}
}
public static void main(String args[])
{
StringBuffer s = new StringBuffer( "GeeksQuiz" );
reverse(s);
System.out.println( "Reversed string is " + s);
}
}
|
Python3
def createStack():
stack = []
return stack
def size(stack):
return len (stack)
def isEmpty(stack):
if size(stack) = = 0 :
return true
def push(stack, item):
stack.append(item)
def pop(stack):
if isEmpty(stack):
return
return stack.pop()
def reverse(string):
n = len (string)
stack = createStack()
for i in range ( 0 , n, 1 ):
push(stack, string[i])
string = ""
for i in range ( 0 , n, 1 ):
string + = pop(stack)
return string
string = "GeeksQuiz"
string = reverse(string)
print ( "Reversed string is " + string)
|
C#
using System;
using System.Text;
class Stack {
public int size;
public int top;
public char [] a;
public Boolean isEmpty() { return (top < 0); }
public Stack( int n)
{
top = -1;
size = n;
a = new char [size];
}
public Boolean push( char x)
{
if (top >= size) {
Console.WriteLine( "Stack Overflow" );
return false ;
}
else {
a[++top] = x;
return true ;
}
}
public char pop()
{
if (top < 0) {
Console.WriteLine( "Stack Underflow" );
return ' ' ;
}
else {
char x = a[top--];
return x;
}
}
}
class GFG {
public static void reverse(StringBuilder str)
{
int n = str.Length;
Stack obj = new Stack(n);
int i;
for (i = 0; i < n; i++)
obj.push(str[i]);
for (i = 0; i < n; i++) {
char ch = obj.pop();
str[i] = ch;
}
}
public static void Main(String[] args)
{
StringBuilder s = new StringBuilder( "GeeksQuiz" );
reverse(s);
Console.WriteLine( "Reversed string is " + s);
}
}
|
Javascript
<script>
class Stack
{
size;
top;
a = [];
isEmpty()
{
return ( this .top < 0);
}
constructor(n)
{
this .top = -1;
this .size = n;
this .a = new Array( this .size);
}
push(x)
{
if ( this .top >= this .size)
{
document.write( "Stack Overflow<br>" );
return false ;
}
else
{
this .a[++ this .top] = x;
return true ;
}
}
pop()
{
if ( this .top < 0)
{
document.write( "Stack Underflow<br>" );
return 0;
}
else
{
let x = this .a[ this .top--];
return x;
}
}
}
function reverse(str)
{
let n = str.length;
let obj = new Stack(n);
let i;
for (i = 0; i < n; i++)
obj.push(str[i]);
for (i = 0; i < n; i++)
{
let ch = obj.pop();
str[i] = ch;
}
}
let s = "GeeksQuiz" .split( "" );
reverse(s);
document.write( "Reversed string is " +
s.join( "" ));
</script>
|
Output
Reversed string is ziuQskeeG
Time Complexity: O(N)
Auxiliary Space: O(N) for Stack.
Reversing The String become Easy If You Use Stack InBulid liberay (STL).
Here in this approach we have use stack(stl) Which is LIFO type DataStructure.
C++
#include <bits/stdc++.h>
#include<iostream>
#include<string>
#include<stack>
using namespace std;
void the_helper(string &str){
stack< char >s;
for ( auto it:str)s.push(it);
str.clear();
while (!s.empty()){
str.push_back(s.top());
s.pop();
}
}
int main() {
string str = "GeeksQuiz" ;
the_helper(str);
cout << "Reversed string is : " << str;
return 0;
}
|
Python3
import string
def the_helper(s):
stack = []
for i in s:
stack.append(i)
s = ""
while stack:
s + = stack.pop()
return s
if __name__ = = "__main__" :
str = "GeeksQuiz"
reversed_str = the_helper( str )
print ( "Reversed string is: " , reversed_str)
|
C#
/// c#
using System;
using System.Collections.Generic;
public class GFG {
static void the_helper( ref string str) {
Stack< char > s = new Stack< char >();
foreach ( char ch in str) {
s.Push(ch);
}
str = "" ;
while (s.Count != 0) {
str += s.Peek();
s.Pop();
}
}
static void Main() {
string str = "GeeksQuiz" ;
the_helper( ref str);
Console.WriteLine( "Reversed string is : " + str);
}
}
|
Javascript
function the_helper(str)
{
let s = [];
for (let i = 0; i < str.length; i++) {
s.push(str.charAt(i));
}
str = '' ;
while (s.length > 0) {
str += s.pop();
}
return str;
}
let str = 'GeeksQuiz' ;
str = the_helper(str);
console.log( 'Reversed string is: ' + str);
|
Java
import java.util.*;
public class Main {
static void the_helper(StringBuilder str){
Stack<Character> s = new Stack<>();
for ( int i= 0 ;i<str.length();i++) s.push(str.charAt(i));
str.delete( 0 , str.length());
while (!s.empty()){
str.append(s.peek());
s.pop();
}
}
public static void main(String[] args) {
StringBuilder str = new StringBuilder( "GeeksQuiz" );
the_helper(str);
System.out.println( "Reversed string is : " + str);
}
}
|
Output
Reversed string is : ziuQskeeG
Time Complexity: O(N) Only one traversal to push and pop so O(n)+O(n)==O(n).
Auxiliary Space: O(N) Extra for Stack.
For other methods, please refer reverse a string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...