Tuesday, July 10, 2012

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

The approach:-
  1. Reverse the entire string.

  2. Scan the string from beginning.

  3. On reaching a word (space) reverse the sub string. Continue till end of the string.

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

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

void reversestring(char* input, int start, int end) {
 while ( start < end ) {
  char c = input[start];
  input[start] = input[end];
  input[end] = c;
  start++;
  end--;
 }
}

void reversewords(char* input) {
 int sz = strlen(input) - 1;
 reversestring(input, 0, sz);

 int word_start = 0;
 int word_end = 0;

 char* ptr = input;
 while ( *ptr !=  '\0' ) {
  if ( *ptr == ' ' ) {
   reversestring(input, word_start, word_end - 1);   
   word_start = word_end + 1;
  }  
  word_end++;
  ptr++;
 } 
 // last word
 reversestring(input, word_start, word_end - 1); 
}

int main() {
 char str[] = "reverse, the words of this string";
 reversewords(str);
 cout << str << endl;
}

Output:-
string this of words the reverse,

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top