Spread the love

Question :- Write a program to reverse string using stack in c++

Algorithm

1) Create an empty stack using Standard Template Library(STL).
2) One by one push all characters of string to stack.
3) One by one pop all characters from stack and put
   them back to string.

Program to reverse string using stack

 

#include<iostream>
#include<string.h>
#include<stack>			//Use Standard template library to create Stack data structure 
using namespace std;

void Reverse(char *p);

int main()
{
	char string[] = "www.firmcodes.com";
	
	Reverse(string);
	
	printf(" %s",string);	
	
	return 0;
}

void Reverse(char *p)
{
	stack<char> S;
	
	/* Pushing to stack */
	for(int i=0; i<strlen(p); i++)		
				S.push(p[i]);
	
	/* Poping from stack */			
	for(int i=0; i<strlen(p); i++)
	{
		p[i] = S.top();
		S.pop();
	}
}

 

Output

Write a program to reverse a string using stack in c++

Suggested Reading

  1. Write a C program to reverse the words in a sentence in place
  2. Write your own trim() or squeeze() function to remove the spaces from a string
  3. Write a C program to reverse the string without using strrev() ?