Hello coders, Let's learn about Stack data structure in a simpler way !!
The stack is a data structure that follows the Last In First Out (LIFO) principle. The element that is added at last is accessed at first. This is like stacking your books on top of each other. The book that you put last comes first.
Examples of stacks in "real life":
The stack of trays in a cafeteria.
A stack of plates in a cupboard.
A driveway that is only one car wide.
The operations that can be performed on stacks are as follows:
Push → Add an element to the stack.
Pop → Delete an element from the stack.
Peek → Get the top element of the stack.
Length → Return the length of the stack.
IsEmpty → Check if the stack is empty.
Clear → To clear the stack.
Now let's jump onto the code.
class Stack {
constructor(){
this.items = [];
}
// To add the element to the stack
push(element) {
return this.items.push(element);
}
// To get the length of the stack
length() {
return this.items.length;
}
// To view the last element
peek() {
return this.items[this.items.length - 1];
}
// To check if last element is empty
isEmpty() {
return this.items.length == 0;
}
// To remove the last element
pop() {
if( this.isEmpty() === false ) {
return this.items.pop();
}
}
// To empty the stack
clear(){
this.items = [];
}
}
console.log("Implementing the stack data structure using JS");
let stack = new Stack();
console.log("To check if stack is empty", stack.isEmpty());
console.log("Adding the elements 5, 25, 50, 75, 100 to the stack");
stack.push(5);
stack.push(25);
stack.push(50);
stack.push(75);
stack.push(100);
console.log("To check the length of the stack", stack.length());
console.log("To view the first element of stack ", stack.peek());
console.log("To remove stack items", stack.pop());
console.log("To clear the stack", stack.clear());
console.log("After clearing the stack - check for isEmpty", stack.isEmpty());