Data Structures
Common data structure implementations and patterns
Linked List Implementation
javascriptBasic singly linked list implementation
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
append(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
print() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
}Binary Search Tree
javascriptBST implementation with basic operations
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new TreeNode(value);
if (!this.root) {
this.root = newNode;
return;
}
let current = this.root;
while (true) {
if (value < current.value) {
if (!current.left) {
current.left = newNode;
break;
}
current = current.left;
} else {
if (!current.right) {
current.right = newNode;
break;
}
current = current.right;
}
}
}
search(value) {
let current = this.root;
while (current) {
if (value === current.value) return true;
if (value < current.value) current = current.left;
else current = current.right;
}
return false;
}
}Stack Implementation
javascriptStack data structure with basic operations
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) return "Stack is empty";
return this.items.pop();
}
peek() {
if (this.isEmpty()) return "Stack is empty";
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
clear() {
this.items = [];
}
}Queue Implementation
javascriptQueue data structure with basic operations
class Queue {
constructor() {
this.items = {};
this.frontIndex = 0;
this.backIndex = 0;
}
enqueue(element) {
this.items[this.backIndex] = element;
this.backIndex++;
}
dequeue() {
if (this.isEmpty()) return "Queue is empty";
const item = this.items[this.frontIndex];
delete this.items[this.frontIndex];
this.frontIndex++;
return item;
}
peek() {
if (this.isEmpty()) return "Queue is empty";
return this.items[this.frontIndex];
}
isEmpty() {
return this.frontIndex === this.backIndex;
}
size() {
return this.backIndex - this.frontIndex;
}
}