Reverse the Words of a String using Stack (original) (raw)

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:

C++ `

//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 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 code int main() { string s="I Love To Code"; reverse(s); return 0; } // This code is contributed by Konderu Hrishikesh.

Java

//Java implementation of // the above approach import 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 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 code public static void main(String[] args) { String s = "I Love To Code"; reverse(s); } }

// This code is contributed by gauravrajput1

Python3

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 code

s = "I Love To Code" reverse(s)

This code is contributed by divyeshrabadiya07

C#

// C# implementation of // the above approach using 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

JavaScript

`

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:

C++ `

// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;

// Function to reverse the words // of the given sentence void 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 code int main() { char k[] = "geeks for geeks"; reverse(k);

return 0;

}

Java

// Java implementation of the approach import 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

Python3 implementation of the approach

Function to reverse the words

of the given sentence

def 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 code

if name == "main" :

k = "geeks for geeks"; 
reverse(k); 

This code is contributed by AnkitRai01

C#

// C# implementation of the approach using 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

JavaScript

`

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