Reverse the Words of a String using Stack | C ++ implementation of the above approach ; function to reverse the words of the given string without using strtok ( ) . ; create an empty string stack ; create an empty temporary string ; traversing the entire string ; push the temporary variable into the stack ; assigning temporary variable as empty ; for the last word of the string ; Get the words in reverse order ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void reverse ( string s ) { stack < string > stc ; string temp = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == ' ▁ ' ) { stc . push ( temp ) ; temp = " " ; } else { temp = temp + s [ i ] ; } } stc . push ( temp ) ; while ( ! stc . empty ( ) ) { temp = stc . top ( ) ; cout << temp << " ▁ " ; stc . pop ( ) ; } cout << endl ; } int main ( ) { string s = " I ▁ Love ▁ To ▁ Code " ; reverse ( s ) ; return 0 ; }