Reverse the Words of a String using Stack
Last Updated :
26 Aug, 2022
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:
- 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++
#include<bits/stdc++.h>
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;
}
|
Java
import java.util.*;
class GFG{
static void reverse(String s)
{
Stack<String> stc = new Stack<>();
String temp = "";
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i) == ' ')
{
stc.add(temp);
temp = "";
}
else
{
temp = temp + s.charAt(i);
}
}
stc.add(temp);
while(!stc.isEmpty())
{
temp = stc.peek();
System.out.print(temp + " ");
stc.pop();
}
System.out.println();
}
public static void main(String[] args)
{
String s = "I Love To Code";
reverse(s);
}
}
|
Python3
def reverse(s):
stc = []
temp = ""
for i in range(len(s)):
if s[i] == ' ':
stc.append(temp)
temp = ""
else:
temp = temp + s[i]
stc.append(temp)
while len(stc) != 0:
temp = stc[len(stc) - 1]
print(temp, end = " ")
stc.pop()
print()
s = "I Love To Code"
reverse(s)
|
C#
using System;
using System.Collections;
class GFG
{
static void reverse(string s)
{
Stack stc = new Stack();
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.Count != 0)
{
temp = (string)stc.Peek();
Console.Write(temp + " ");
stc.Pop();
}
Console.WriteLine();
}
static void Main()
{
string s = "I Love To Code";
reverse(s);
}
}
|
Javascript
<script>
function reverse(s)
{
let stc = [];
let temp = "";
for(let i = 0; i < s.length; i++)
{
if(s[i] == ' ')
{
stc.push(temp);
temp = "";
}
else
{
temp = temp + s[i];
}
}
stc.push(temp);
while(stc.length != 0)
{
temp = stc[stc.length - 1];
document.write(temp + " ");
stc.pop();
}
}
let s = "I Love To Code";
reverse(s);
</script>
|
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:
- 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++
#include <bits/stdc++.h>
using namespace std;
void reverse(char k[])
{
stack<char*> s;
char* token = strtok(k, " ");
while (token != NULL) {
s.push(token);
token = strtok(NULL, " ");
}
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
}
int main()
{
char k[] = "geeks for geeks";
reverse(k);
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Stack;
class GFG {
static void reverse(String k)
{
Stack<String> s = new Stack<>();
String[] token = k.split(" ");
for (int i = 0; i < token.length; i++) {
s.push(token[i]);
}
while (!s.empty()) {
System.out.print(s.peek() + " ");
s.pop();
}
}
public static void main(String[] args)
{
String k = "geeks for geeks";
reverse(k);
}
}
|
Python3
def reverse(k):
s = []
token = k.split()
for word in token :
s.append(word);
while (len(s)) :
print(s.pop(), end = " ");
if __name__ == "__main__" :
k = "geeks for geeks";
reverse(k);
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void reverse(String k)
{
Stack<String> s = new Stack<String>();
String[] token = k.Split(' ');
for (int i = 0; i < token.Length; i++) {
s.Push(token[i]);
}
while (s.Count != 0) {
Console.Write(s.Peek() + " ");
s.Pop();
}
}
public static void Main(String[] args)
{
String k = "geeks for geeks";
reverse(k);
}
}
|
Javascript
<script>
function reverse(k)
{
let s = [];
let token = k.split(" ");
for (let i = 0; i < token.length; i++) {
s.push(token[i]);
}
while (s.length > 0) {
document.write(s[s.length - 1] + " ");
s.pop();
}
}
let k = "geeks for geeks";
reverse(k);
</script>
|
Time Complexity: O(N), for traversing over the string.
Auxiliary Space: O(N), for storing the words in the string.
Share your thoughts in the comments
Please Login to comment...