Already we have seen stack data structure in detail. Now let’s jump into reverse a string using stack.
To reverse a string using Stack:
- Create an empty stack.
- Using push function push all the characters of the string to stack.
- Using pop function remove all the characters of the string back.
function reverse(str){
let stack = [];
//push letter into stack
for (let i=0; i<str.length; i++){
stack.push(str[i]);
}
//pop letter from the stack
let reverseStr = '';
while(stack.length > 0){
reverseStr += stack.pop();
}
return reverseStr;
}
console.log(reverse('Abaython'));