0% found this document useful (0 votes)
30 views1 page

Reverse Words in String with Stack

The document describes reversing the words in a string using a stack data structure. It provides code to detect the ends of words and push them onto a stack before printing the stack contents to output the words in reverse order.

Uploaded by

Dipak Nandeshwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views1 page

Reverse Words in String with Stack

The document describes reversing the words in a string using a stack data structure. It provides code to detect the ends of words and push them onto a stack before printing the stack contents to output the words in reverse order.

Uploaded by

Dipak Nandeshwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

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

You might also like