In this write-up, we are going to see how the stack data structure can be implemented in Javascript.
What is a Stack?
The stack is a data structure to store the data in the order of insertion where the item gets inserted at the last into the stack will be the first one to be removed.
In shorter terms Last In First Out(LIFO).
How are we going to implement it?
The following are the methods that we are going to implement in Stack DS.
initialize β Initialize the storage and stack size
push β push data to the stack
pop β Remove the last pushed item from the stack
getStackSize β Get the current stack size
initialize
class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}
}
push
class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}
/* Add item to the stack */
push(item) {
this.storage[this.stackLength] = item;
this.stackLength++;
}
}
pop
class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}
/* Remove Item from the stack with below conditions
1. Get the last index
2. check the stack is non-empty
3. remove the item from the storage
*/
pop() {
let endIndex = this.stackLength - 1;
if (endIndex >= 0) {
delete this.storage[endIndex]
this.stackLength--;
} else {
throw "Stack is Empty, cannot pop!"
}
}
}
getStackSize
class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}
/* To get the stack size */
getStackSize() {
return this.stackLength;
}
}
Top comments (0)