VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-the-sentence-using-stack/

⇱ Reverse the Words of a String using Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse the Words of a String using Stack

Last Updated : 12 Jul, 2025

Given string str consisting of multiple words, the task is to reverse the entire string word by word.
Examples:  

Input: str = "I Love To Code" 
Output: Code To Love I
Input: str = "data structures and algorithms" 
Output: algorithms and structures data 
 

Approach: This problem can be solved not only with the help of the strtok() but also it can be solved by using Stack Container Class in STL C++ by following the given steps:  

  1. Create an empty stack.
  2. Traverse the entire string, while traversing add the characters of the string into a temporary 
    variable until you get a space(' ') and push that temporary variable into the stack.
  3. Repeat the above step until the end of the string.
  4. Pop the words from the stack until the stack is not empty which will be in reverse order.

Below is the implementation of the above approach: 
 


Output: 
Code To Love I

 

Time Complexity: O(N), for traversing over the string.
Auxiliary Space: O(N), for storing the words in the string.

Another Approach: An approach without using stack is discussed here. This problem can also be solved using stack by following the below steps: 
 

  1. Create an empty stack.
  2. Tokenize the input string into words using spaces as separator with the help of strtok()
  3. Push the words into the stack.
  4. Pop the words from the stack until the stack is not empty which will be in reverse order.


Below is the implementation of the above approach: 
 


Output: 
geeks for geeks

 

Time Complexity: O(N), for traversing over the string.
Auxiliary Space: O(N), for storing the words in the string.

Comment
Article Tags:
Article Tags: