How to use Stack for Reversal In Javascript
In this approach, we iterate through each character of the input sentence and use a stack to reverse the characters of each word. When we encounter a space, we pop all characters from the stack to get the reversed word and add it to the result string. Finally, we handle the last word separately after the loop.
Example: Implementation of a program to reverse all the words of a sentence using a stack.
function reverseWithStack(sentence) {
let stack = [];
let reversed = "";
for (let i = 0; i < sentence.length; i++) {
if (sentence[i] !== " ") {
stack.push(sentence[i]);
} else {
while (stack.length > 0) {
reversed += stack.pop();
}
reversed += " ";
}
}
while (stack.length > 0) {
reversed += stack.pop();
}
return reversed;
}
let input = "Hello World";
let output = reverseWithStack(input);
console.log(output);
Output
olleH dlroW
Reverse all the Words of Sentence JavaScript
Given a sentence, Our task is to reverse all the words in the sentence while maintaining their order.
Example:
Input: "Hello World"
Output: "olleH dlroW"
Below are the approaches to reverse all the words of sentence JavaScript:
Table of Content
- Using Built-in Functions
- Using Iterative Reversal