Data Structures Implementation in Javascript Part 2
This blog post will discuss how to implement Stacks and Queues in Javascript.
Stack
A stack is a linear data structure represented by a real physical stack or pile, a structure where insertion and deletion of items takes place at one end called top of the stack. The basic implementation of a stack is LIFO (Last In First Out) to demonstrate the way it accesses data. A basic stack implementation has 2 actions: inserting an item into a stack and deleting an item from the stack.
All operations are O(1).
Properties
push — function — Accepts a value and adds a new item on top of the stack
pop — function — Removes the top item from the stack
isEmpty — function — Checks if the stack is empty
size — function — Counts the number of items on the stack
Javascript Implementation
class Stack {constructor() {
this.stack = []
}push(value) {
this.stack.push(value)
}pop() {
this.stack.pop()
}isEmpty() {
if (this.stack.length === 0) {
return true
} else {
return false
}
}size() {
return this.stack.length
}serialize() {
return this.stack
}
}let stack = new Stack()
stack.push(1)
stack.push(2)
console.log(stack.serialize());
stack.push(3)
console.log(stack.isEmpty());
console.log(stack.size());
console.log(stack.serialize());
stack.pop()
console.log(stack.serialize());
stack.pop()
stack.pop()
console.log(stack.serialize());
console.log(stack.isEmpty());
Output
[ 1, 2 ]false3[ 1, 2, 3 ][ 1, 2 ][]true
Queue
A queue is a linear data structure in which the first element is inserted from one end, called the rear (also called tail), and the removal of existing element takes place from the other end, called the front (also called head). A queue is a FIFO(First in First Out) data structure, which means that element inserted first will be removed first.
All operations are O(1).
Properties
enqueue — function — Accepts a value and adds an element to the queue
dequeue — function — Removes an element from the front of the queue
peek — function — Gets the front element in the queue
empty — function — Checks if the queue is empty
Javascript Implementation
class Queue {constructor() {
this.queue = []
}enqueue(value) {
this.queue.push(value)
}dequeue() {
let removed = this.queue[0]
this.queue.shift()
return removed
}peek() {
return this.queue[0]
}empty() {
if (this.queue.length === 0) {
return true
} else {
return false
}
}serialize() {
return this.queue
}
}let queue = new Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
console.log(queue.serialize());
console.log(queue.peek());
console.log(queue.empty());
queue.dequeue()
console.log(queue.serialize());
queue.dequeue()
queue.dequeue()
console.log(queue.serialize());
console.log(queue.empty());
Output
[ 1, 2, 3 ]1false[ 2, 3 ][]true
Thanks for reading!