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'));
We have already seen about Array Data Structure. Stack data structure is implemented using arrays. With push(), pop(), shift(), unshift() we create stack . For creation of stack we always prefer push() and pop(). Now let us implement stack data structure.
Methods to implement Stack Data Structure :
push() – adds an element at top of the stack
pop() – removes the top most element of the stack and if it is called on an empty stack returns ‘underflow’
peek() – similar to pop() returns top most element but does not delete it.
isEmpty() – return true if stack is empty.
printStack() – returns a string in which all elements of the stack are concatenated.
Program to implement Stack :
class Stack {
constructor() {
this.items = [];
}
// add element to the stack
add(element) {
return this.items.push(element);
}
// remove element from the stack
remove() {
if(this.items.length > 0) {
return this.items.pop();
}
}
// view the last element
peek() {
return this.items[this.items.length - 1];
}
// check if the stack is empty
isEmpty(){
return this.items.length == 0;
}
// the size of the stack
size(){
return this.items.length;
}
// empty the stack
clear(){
this.items = [];
}
}
let stack = new Stack();
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
console.log(stack.items);
stack.remove();
console.log(stack.items);
console.log(stack.peek());
console.log(stack.isEmpty());
console.log(stack.size());
stack.clear();
console.log(stack.items);