Tuesday, July 10, 2012
SourceTricks at Tuesday, July 10, 2012
Reverse words of a string using 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.
#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