Table of contents
Introduction
The stack data structure is a sequential collection of elements that follows the principle of Last In First Out (LIFO).
The last element inserted into the stack is first element to be removed.
A stack of plates. The last plate placed on top of the stack is also the first plate removed from the stack.
Operations
push(element)
: add an element to the toppop()
: remove the top most elementpeek()
: get the value of the top element without removing itisEmpty()
: check if is emptysize()
: get the number of elementsprint()
: visualise the elements
Code
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
print() {
console.log(this.items.toString());
}
}
const stack = new Stack();
console.log(stack.isEmpty()); // true
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
console.log(stack); // { items: [ 10, 20, 30, 40 ] }
console.log(stack.isEmpty()); // false
stack.pop();
console.log(stack); // { items: [ 10, 20, 30 ] }
console.log(stack.peek()); // 30
Usage
Browser history tracking
Undo operation when typing
Expression conversions
Call stack in JavaScript runtime
ย