Алгоритмы и структуры данных на JavaScript: от теории к практике
Умение работать с алгоритмами и структурами данных — ключевой навык любого разработчика, независимо от языка программирования. JavaScript (особенно в среде Node.js) не является исключением. В этой статье мы разберём фундаментальные структуры данных и классические алгоритмы, реализовав их на чистом JavaScript. Вы увидите, как стек, очередь, связный список, дерево и алгоритмы сортировки/поиска применяются в реальных задачах бэкенд-разработки на Node.js.
1. Стек и очередь: базовые структуры для управления данными
Стек (Stack) и очередь (Queue) — это линейные структуры данных, которые отличаются правилами добавления и удаления элементов. Стек работает по принципу LIFO (Last In, First Out), а очередь — FIFO (First In, First Out).
Реализация стека на JavaScript
В JavaScript стек можно реализовать на основе массива или связного списка. Рассмотрим простой вариант с массивом:
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) return null;
return this.items.pop();
}
peek() {
if (this.isEmpty()) return null;
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
// Пример использования
const stack = new Stack();
stack.push('A');
stack.push('B');
stack.push('C');
console.log(stack.pop()); // 'C'
console.log(stack.peek()); // 'B'
Стек часто применяется для проверки сбалансированности скобок, реализации кнопки "Назад" в браузере или для обхода деревьев в глубину.
Реализация очереди на JavaScript
Очередь также можно построить на массиве, но для лучшей производительности (избегая переиндексации при shift) используем связный список или два стека. Вот простая реализация на массиве:
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
if (this.isEmpty()) return null;
return this.items.shift();
}
front() {
if (this.isEmpty()) return null;
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
// Пример использования
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log(queue.dequeue()); // 1
console.log(queue.front()); // 2
Очереди используются в системах управления задачами, в алгоритмах BFS (обход в ширину) и для буферизации данных в Node.js (например, потоки).
2. Связный список: динамическая структура для частых вставок
Связный список (Linked List) — это последовательность узлов, каждый из которых содержит данные и ссылку на следующий узел. В отличие от массива, вставка и удаление элементов в середине списка выполняются за O(1) при наличии ссылки на узел.
Реализация односвязного списка
class ListNode {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
append(value) {
const newNode = new ListNode(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
return this;
}
prepend(value) {
const newNode = new ListNode(value, this.head);
this.head = newNode;
if (!this.tail) this.tail = newNode;
this.length++;
return this;
}
find(value) {
let current = this.head;
while (current) {
if (current.value === value) return current;
current = current.next;
}
return null;
}
delete(value) {
if (!this.head) return null;
let deletedNode = null;
while (this.head && this.head.value === value) {
deletedNode = this.head;
this.head = this.head.next;
this.length--;
}
let current = this.head;
if (current) {
while (current.next) {
if (current.next.value === value) {
deletedNode = current.next;
current.next = current.next.next;
this.length--;
} else {
current = current.next;
}
}
}
if (this.tail?.value === value) this.tail = current;
return deletedNode;
}
toArray() {
const result = [];
let current = this.head;
while (current) {
result.push(current.value);
current = current.next;
}
return result;
}
}
// Пример использования
const list = new LinkedList();
list.append(10).append(20).prepend(5);
console.log(list.toArray()); // [5, 10, 20]
list.delete(10);
console.log(list.toArray()); // [5, 20]
Связные списки лежат в основе более сложных структур (например, хэш-таблиц для разрешения коллизий) и используются в реализации очередей с приоритетом.
3. Дерево бинарного поиска и рекурсивные алгоритмы
Дерево бинарного поиска (BST) — это иерархическая структура, где каждый узел имеет не более двух потомков. Левое поддерево содержит меньшие значения, правое — большие. Это позволяет выполнять поиск, вставку и удаление за O(log n) в среднем.
Реализация BST
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 this;
}
let current = this.root;
while (true) {
if (value === current.value) return undefined;
if (value < current.value) {
if (!current.left) {
current.left = newNode;
return this;
}
current = current.left;
} else {
if (!current.right) {
current.right = newNode;
return this;
}
current = current.right;
}
}
}
find(value) {
if (!this.root) return false;
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;
}
// Обход в глубину (in-order)
inOrder(node = this.root, result = []) {
if (node) {
this.inOrder(node.left, result);
result.push(node.value);
this.inOrder(node.right, result);
}
return result;
}
// Обход в ширину (BFS)
breadthFirst() {
if (!this.root) return [];
const queue = [this.root];
const result = [];
while (queue.length) {
const node = queue.shift();
result.push(node