Reverse individual words using Stack in C++

Hello Guys, In this tutorial we are going to learn how to reverse individual words using stack in c++?  Before that check this tutorial on stacks to have a better understanding of the problem. Although we will see some functions of stacks here yet read that tutorial first.

Stacks are the data structures that follow the LIFO (Last in first out) order. It means that when we will add the element to a stack it will take the top position and whenever we will delete an element it will be deleted from the top. Below are some functions of stacks that we will use to reverse the individual words in c++. We can include a stack in our program using a header file #include<stack>.

  1. push(x) – it will insert x to the top of the stack.
  2. pop() – it will delete the top element in the stack.
  3. top() – it is used to access the top element of the stack.
  4. size() – it will return the size of the stack.

Now let us understand the problem, we are given a word/string and we have to invert it.
For Example;

string s= "codespeedy";
After Inversion
s="ydeepsedoc";

There are several methods to do this but we will discuss the method using stack.

Algorithm to Reverse individual words using Stack in C++

Algorithm

  • First, we will define an empty stack and will insert string’s characters into that stack.
  • Then we will access the stack and will insert its characters into an empty string.
  • We will simultaneously delete its characters from the top.
  • Finally, we will print the string formed.

The time complexity of the algorithm – O(n).

Code in C++

#include<iostream>
#include<string>
#include<stack>
using namespace std;

int main(){
    string s="codespeedy";
    int n=s.length();

    cout<<"Given string - \n";
    cout<<s<<"\n";

    stack<int> p;  // empty stack
    for(int x=0; x<n; x++){     
        p.push(s[x]);
    }
    s="";  // empty string

    for(int x=0; x<n; x++){
        s+=p.top();
        p.pop();
    }

    cout<<"Inverted String - \n";
    cout<<s<<"\n";

    return 0;
}

Output

Given string -
codespeedy
Inverted String -
ydeepsedoc

This is it for this tutorial.
Hope it will help you.
Also, check out some of my other blogs.

Leave a Reply

Your email address will not be published. Required fields are marked *