Reverse the Words of a String using Stack

30 Jun, 2021
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 IInput: 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:  
Create an empty stack.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.Repeat the above step until the end of the string.Pop the words from the stack until the stack is not empty which will be in reverse order.
Create an empty stack.
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.
Repeat the above step until the end of the string.
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:  
C++
Java
Python3
C#
Javascript
//C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; //function to reverse the words//of the given string without using strtok().void reverse(string s){  //create an empty string stack  stack<string> stc;   //create an empty temporary string  string temp="";   //traversing the entire string  for(int i=0;i<s.length();i++)  {    if(s[i]==' ')    {             //push the temporary variable into the stack      stc.push(temp);             //assigning temporary variable as empty      temp="";             }    else    {      temp=temp+s[i];    }   }   //for the last word of the string  stc.push(temp);   while(!stc.empty()) {     // Get the words in reverse order    temp=stc.top();    cout<<temp<<" ";    stc.pop();  }  cout<<endl;} //Driver codeint main(){  string s="I Love To Code";  reverse(s);  return 0;}// This code is contributed by Konderu Hrishikesh.
//Java implementation of// the above approachimport java.util.*;class GFG{ // Function to reverse the words// of the given String without// using strtok().static void reverse(String s){  // Create an empty String stack  Stack<String> stc = new Stack<>();   // Create an empty temporary String  String temp = "";   // Traversing the entire String  for(int i = 0; i < s.length(); i++)  {    if(s.charAt(i) == ' ')    {             // Push the temporary      // variable into the stack      stc.add(temp);             // Assigning temporary      // variable as empty      temp = "";             }    else    {      temp = temp + s.charAt(i);    }   }   // For the last word  // of the String  stc.add(temp);   while(!stc.isEmpty())  {    // Get the words in    // reverse order    temp = stc.peek();    System.out.print(temp + " ");    stc.pop();  }     System.out.println();} //Driver codepublic static void main(String[] args){  String s = "I Love To Code";  reverse(s);}} // This code is contributed by gauravrajput1
# Python3 implementation of# the above approach # function to reverse the# words of the given string# without using strtok().def reverse(s):   # create an empty string  # stack  stc = []   # create an empty temporary  # string  temp = ""   # traversing the entire string  for i in range(len(s)):      if s[i] == ' ':             # push the temporary variable      # into the stack      stc.append(temp)             # assigning temporary variable      # as empty      temp = ""              else:      temp = temp + s[i]   # for the last word of the string  stc.append(temp)   while len(stc) != 0:     # Get the words in reverse order    temp = stc[len(stc) - 1]    print(temp, end = " ")    stc.pop()     print() # Driver codes = "I Love To Code"reverse(s) # This code is contributed by divyeshrabadiya07
// C# implementation of// the above approachusing System;using System.Collections; class GFG{         // Function to reverse the words    // of the given String without    // using strtok().    static void reverse(string s)    {             // Create an empty String stack      Stack stc = new Stack();            // Create an empty temporary String      string temp = "";            // Traversing the entire String      for(int i = 0; i < s.Length; i++)      {        if(s[i] == ' ')        {                      // Push the temporary          // variable into the stack          stc.Push(temp);                      // Assigning temporary          // variable as empty          temp = "";                 }        else        {          temp = temp + s[i];        }            }            // For the last word      // of the String      stc.Push(temp);            while(stc.Count != 0)      {                 // Get the words in        // reverse order        temp = (string)stc.Peek();        Console.Write(temp + " ");        stc.Pop();      }              Console.WriteLine();    }   // Driver code  static void Main()  {    string s = "I Love To Code";    reverse(s);  }} // This code is contributed by divyesh072019
<script>     // Javascript implementation of    // the above approach           // Function to reverse the words    // of the given String without    // using strtok().    function reverse(s)    {              // Create an empty String stack      let stc = [];             // Create an empty temporary String      let temp = "";             // Traversing the entire String      for(let i = 0; i < s.length; i++)      {        if(s[i] == ' ')        {                       // Push the temporary          // variable into the stack          stc.push(temp);                       // Assigning temporary          // variable as empty          temp = "";                }        else        {          temp = temp + s[i];        }             }             // For the last word      // of the String      stc.push(temp);             while(stc.length != 0)      {                  // Get the words in        // reverse order        temp = stc[stc.length - 1];        document.write(temp + " ");        stc.pop();      }    }         let s = "I Love To Code";    reverse(s);     </script>
Code To Love I
 
Time Complexity: O(N)
Another Approach: An approach without using stack is discussed here. This problem can also be solved using stack by following the below steps:  
Create an empty stack.Tokenize the input string into words using spaces as separator with the help of strtok()Push the words into the stack.Pop the words from the stack until the stack is not empty which will be in reverse order.
Create an empty stack.
Tokenize the input string into words using spaces as separator with the help of strtok()
Push the words into the stack.
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:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to reverse the words// of the given sentencevoid reverse(char k[]){     // Create an empty character array stack    stack<char*> s;    char* token = strtok(k, " ");     // Push words into the stack    while (token != NULL) {        s.push(token);        token = strtok(NULL, " ");    }     while (!s.empty()) {         // Get the words in reverse order        cout << s.top() << " ";        s.pop();    }} // Driver codeint main(){    char k[] = "geeks for geeks";    reverse(k);     return 0;}
// Java implementation of the approachimport java.util.Arrays;import java.util.Stack; class GFG {     // Function to reverse the words    // of the given sentence    static void reverse(String k)    {         // Create an empty character array stack        Stack<String> s = new Stack<>();        String[] token = k.split(" ");         // Push words into the stack        for (int i = 0; i < token.length; i++) {            s.push(token[i]);        }         while (!s.empty()) {             // Get the words in reverse order            System.out.print(s.peek() + " ");            s.pop();        }    }     // Driver code    public static void main(String[] args)    {        String k = "geeks for geeks";        reverse(k);    }} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to reverse the words# of the given sentencedef reverse(k):    # Create an empty character array stack    s = []    token = k.split()         # Push words into the stack    for word in token :        s.append(word);             while (len(s)) :        # Get the words in reverse order        print(s.pop(), end = " ");      # Driver codeif __name__ == "__main__" :     k = "geeks for geeks";    reverse(k);     # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG {     // Function to reverse the words    // of the given sentence    static void reverse(String k)    {         // Create an empty character array stack        Stack<String> s = new Stack<String>();        String[] token = k.Split(' ');         // Push words into the stack        for (int i = 0; i < token.Length; i++) {            s.Push(token[i]);        }         while (s.Count != 0) {             // Get the words in reverse order            Console.Write(s.Peek() + " ");            s.Pop();        }    }     // Driver code    public static void Main(String[] args)    {        String k = "geeks for geeks";        reverse(k);    }} // This code is contributed by PrinciRaj1992
<script>     // JavaScript implementation of the approach     // Function to reverse the words    // of the given sentence    function reverse(k)    {         // Create an empty character array stack        let s = [];          let token = k.split(" ");         // Push words into the stack        for (let i = 0; i < token.length; i++) {            s.push(token[i]);        }          while (s.length > 0) {              // Get the words in reverse order            document.write(s[s.length - 1] + " ");            s.pop();        }    }     // Driver code    let k = "geeks for geeks";    reverse(k); </script>
geeks for geeks
 
Time Complexity: O(N)
Rajput-Ji
ankthon
princiraj1992
hrishikeshkonderu
GauravRajput1
divyeshrabadiya07
divyesh072019
mukesh07
vaibhavrabadiya117
Stack
Strings
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Design a stack with operations on middle element
How to efficiently implement k stacks in a single array?
Next Smaller Element
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++