Reverse a String Using Stack
“Reverse a String Using Stack” is a basic programming exercise problem based on stack data structure. Here, in this problem, we are given a string and our task is to reverse a given string using stack data structure.
Example:
String: Helpmestudybro Reversed String: orbydutsempleH String: Programming is cool Reverse String: looc si gnimmargorP
The steps required to Reverse a String using stack are as follows:
- Create an empty character stack.
- Push all the characters of the string into the stack.
- Nullify the given string.
- Pop and concatenate all the character from the stack to given string.
- Return and print the result.
The time complexity of this solution is O(n) and it is using O(n) extra space.
C++ Program to Reverse a String Using Stack is as follows:
/* C++ Program to Reverse a String Using String */
#include<bits/stdc++.h>
using namespace std;
/* Function to Reverse a Stack */
string reverseUsingStack(string str)
{
/* Create an empty character Stack */
stack<char> st;
/* Push all the character of the string into stack */
for(int i = 0; i < str.length(); i++)
{
st.push(str[i]);
}
/* Nullify a string */
str = "";
/* Pop and concatenate all characters of the stack */
while(!st.empty())
{
str = str + st.top();
st.pop();
}
/* Return the reverse string */
return str;
}
int main()
{
string str = "helpmestudybro is an emerging website";
string reverse_string = reverseUsingStack(str);
cout<<"The Reversed String is:\n"<<reverse_string;
}
OUTPUT: The Reversed String is: etisbew gnigreme na si orbydutsempleh
Related Posts:
- Implement two stacks in a single array
- Print Bracket Number
- Next Greater Frequency Element
- Sort a Stack using Temporary Stack
- Infix to Postfix Conversion
- Infix to Prefix Conversion
- Prefix to Infix Conversion
- Prefix to Postfix Conversion
- Postfix to Infix Conversion
- Postfix to Prefix Conversion
- Check whether given Parentheses String are Balanced Parentheses or Not.
- Next Greater Element
- Find Minimum number of bracket reversals required to make an expression balanced.
- Implement Queue Using Two Stacks.
- Find First Non-Repeating Character of the String.
- Find Most Frequent Element of the Array.
- Merge Overlapping Intervals using Stacks
- Implement Stack Using Linked List
- Largest Rectangular Area in Histogram
- Length of Longest Valid Substring