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:

  1. Create an empty character stack.
  2. Push all the characters of the string into the stack.
  3. Nullify the given string.
  4. Pop and concatenate all the character from the stack to given string.
  5. 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:

  1. Implement two stacks in a single array
  2. Print Bracket Number
  3. Next Greater Frequency Element
  4. Sort a Stack using Temporary Stack
  5. Infix to Postfix Conversion
  6. Infix to Prefix Conversion
  7. Prefix to Infix Conversion
  8. Prefix to Postfix Conversion
  9. Postfix to Infix Conversion
  10. Postfix to Prefix Conversion
  11. Check whether given Parentheses String are Balanced Parentheses or Not.
  12. Next Greater Element
  13. Find Minimum number of bracket reversals required to make an expression balanced.
  14. Implement Queue Using Two Stacks.
  15. Find First Non-Repeating Character of the String.
  16. Find Most Frequent Element of the Array.
  17. Merge Overlapping Intervals using Stacks
  18. Implement Stack Using Linked List
  19. Largest Rectangular Area in Histogram
  20. Length of Longest Valid Substring

You may also like...