Stack data structure resembles the real world stacking of things like papers. The item which is last inserted into the stack will come out first, the principle is called Last In First Out(LIFO).
Implementation
Firstly we create a class for implementation in javascript and then creating three data members top, capacity and an empty array of five undefined items.
class Stack{
constructor(){
this.top = 0;
this.items = new Array(5);
this.capacity = 5;
}
}
Functions
The Stack should contain functions for adding an item at the top(push), removing an element from top(pop), check if the stack is empty, check if the stack is full and get the top element of the stack(peek)
isEmpty() {
if (this.top === 0) return true;
else return false;
}
isFull() {
if (this.top === this.capacity) return true;
else return false;
}
push(item) {
if (this.isFull() === true) {
console.log("Stack Overflow");
} else {
this.items[this.top] = item;
this.top += 1;
}
}
pop() {
if (this.isEmpty() === true) {
return "Stack Underflow";
} else {
let item = this.items[this.top - 1];
delete this.items[this.top - 1];
this.top -= 1;
return item;
}
}
peek() {
return this.items[this.top - 1];
}
Why we need Stack?
Pushing the element and popping out the element in the stack takes place in a constant time O(1). One of the real time example of stack is browser history, when you click back the site you visited last appears.
Follow me for awesome content on coding.
Top comments (0)