Reverse a sentence using stack in js

44 Views Asked by At

I have wanted to reverse a sentence using Stack in JavaScript, so here if I give input, Hey, how are you doing? and want to get output done? You are hey, so I traverse the loop and check until space is found, then push that word, then pop all the words from the stack, but it's not showing the undefined, so how can you please rectify that code?

function reverseSentence(S){
    let stack = [];
    let word="";
    for(let i=0;i<S.length;i++){
        while(S[i]!=' '&&i<S.length){ 
            word+=S[i]
            i++
        }
       return stack.push(word)
    }
    while(!stack.length){
       return stack.pop()
    }
}
console.log(reverseSentence("Hey, how are you doing?"))
1

There are 1 best solutions below

0
Jaromanda X On BEST ANSWER

The simplest way to achieve what you are after is possibly

function reverseSentence(S){
    return S.split(" ").reverse().join(" ");
}
console.log(reverseSentence("Hey, how are you doing?"));

However, since you use the word "stack", the following shows how to use array's push/pop to achieve the same goal

function reverseSentence(S){
    const stack = [];
    for(let i=0;i<S.length;i++){
        let word="";
        while(S[i]!=' '&&i<S.length){ 
            word+=S[i]
            i++
        }
       stack.push(word)
    }
    let reverse = stack.pop();
    while(stack.length){
       reverse += " " + stack.pop();
    }
    return reverse;
}
console.log(reverseSentence("Hey, how are you doing?"))