Tuesday, July 10, 2012

Write a program to reverse words of a string using a stack

The simplest approach to reverse words of a string is using a stack. To understand more about stack data structure refer C++ Stacks. Detect end of words and push into the stack. Then parse the contents of stack and print to get the string reversed.

C++ program to reverse words of a string using a stack

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

int main() {
 char input[] = "this  is a   test";
 int sz = sizeof(input) / sizeof(char) - 1;
 stack<string> s;
 char word[sz];
 int j = 0;
 for ( int i = 0; i <= sz; i++ ) { 
  if ( input[i] != ' ' && input[i] != '\0' ) {
   word[j++] = input[i];
  }
  else {
   word[j++] = '\0';   
   s.push(word);
   j = 0;
  }
 }

 while ( ! s.empty() ) {
  string w = s.top();
  s.pop();
  cout << w << " ";
 }
}


Output:-
test   a is  this

1 comment :

  1. FYI, the string parsing part can be simplified:

    stringstream ss;
    ss << "This is a test";
    string w;
    while (ss >> w)
    {
    s.push(w);
    }

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top