JavaScript可通过数组、对象和类实现核心数据结构:数组适合索引访问,链表利于频繁增删;栈用数组实现LIFO,队列用对象优化FIFO;二叉树支持递归遍历,图用邻接表存储;并可基于这些结构实现递归、排序、搜索等算法。

JavaScript 是一门灵活且强大的编程语言,非常适合用来实现各种数据结构与算法。通过合理使用 JavaScript 的对象、数组和函数特性,我们可以高效地构建常见数据结构,并在此基础上实现经典算法。以下是几种核心数据结构及其在 JavaScript 中的实现方式。
数组是 JavaScript 中最基础的数据结构之一,基于索引访问非常快,但在插入或删除时效率较低,尤其是在头部或中间位置。
常见操作:链表通过节点连接实现,每个节点包含值和指向下一个节点的指针。适合频繁插入删除的场景。
简易单向链表实现:
class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
<p>class LinkedList {
constructor() {
this.head = null;
}</p><p>append(val) {
const node = new ListNode(val);
if (!this.head) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
}
}</p>栈遵循后进先出(LIFO)原则,可以用数组快速实现。
立即学习“Java免费学习笔记(深入)”;
实现示例:
class Stack {
constructor() {
this.items = [];
}
<p>push(item) {
this.items.push(item);
}</p><p>pop() {
return this.items.pop();
}</p><p>peek() {
return this.items[this.items.length - 1];
}</p><p>isEmpty() {
return this.items.length === 0;
}
}</p>队列是先进先出(FIFO)结构。虽然可用数组实现,但 shift() 操作为 O(n),建议用对象加指针优化。
优化队列实现:
class Queue {
constructor() {
this.items = {};
this.head = 0;
this.tail = 0;
}
<p>enqueue(val) {
this.items[this.tail] = val;
this.tail++;
}</p><p>dequeue() {
if (this.head === this.tail) return undefined;
const val = this.items[this.head];
delete this.items[this.head];
this.head++;
return val;
}
}</p>二叉树每个节点最多有两个子节点。常用于搜索、排序等场景。
二叉树节点定义:
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
常见遍历方式包括递归实现的前序、中序、后序遍历,以及用队列实现的层序遍历(广度优先)。
图可以用邻接表或邻接矩阵表示。JavaScript 中常用对象存储邻接表。
无向图实现示例:
class Graph {
constructor() {
this.adjacencyList = {};
}
<p>addVertex(vertex) {
if (!this.adjacencyList[vertex]) {
this.adjacencyList[vertex] = [];
}
}</p><p>addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
}</p>在数据结构基础上,可实现多种经典算法。
递归与回溯:排序算法:
搜索算法:
基本上就这些。掌握这些基础结构和实现方法,能应对大多数前端或算法题场景。关键是理解每种结构的适用条件和性能特点。
以上就是JavaScript数据结构与算法实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号