在JavaScript中,常见的数据结构实现包括数组、链表、栈、队列、哈希表(对象或Map)、集合(Set)、树(如二叉树)、图等。下面我将逐一简要介绍这些数据结构的基本实现。
1. 数组
JavaScript 的数组是动态的,可以自动调整大小。
let arr = [1, 2, 3];
arr.push(4); // 添加元素
console.log(arr); // 输出: [1, 2, 3, 4]
2. 链表
链表是一种在物理上非连续、非顺序的数据结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。
class Node { constructor(value) { this.value = value; this.next = null; }
} class LinkedList { constructor() { this.head = null; } append(value) { let newNode = new Node(value); if (!this.head) { this.head = newNode; } else { let current = this.head; while (current.next) { current = current.next; } current.next = newNode; } }
} let list = new LinkedList();
list.append(1);
list.append(2);
3. 栈
栈是一种后进先出(LIFO)的数据结构。
class Stack { constructor() { this.items = []; } push(element) { this.items.push(element); } pop() { if (this.items.length == 0) return "Underflow"; return this.items.pop(); } peek() { return this.items[this.items.length - 1]; } isEmpty() { return this.items.length == 0; } size() { return this.items.length; }
} let stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 输出: 2
4. 队列
队列是一种先进先出(FIFO)的数据结构。
class Queue { constructor() { this.items = []; } enqueue(element) { this.items.push(element); } dequeue() { if (this.isEmpty()) return "Underflow"; return this.items.shift(); } front() { return this.items[0]; } isEmpty() { return this.items.length == 0; } size() { return this.items.length; }
} let queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.dequeue()); // 输出: 1
5. 哈希表
JavaScript 的对象或ES6中的Map
可以充当哈希表。
let map = new Map();
map.set('key', 'value');
console.log(map.get('key')); // 输出: value
6. 集合
JavaScript 的 Set
对象允许你存储任何类型的唯一值,无论是原始值还是对象引用。
let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // 2不会被再次添加
console.log(mySet); // 输出: Set(2) {1, 2}
7. 树
树是一种广泛使用的数据结构,模拟具有根节点和子节点的层次结构。
class TreeNode { constructor(value) { this.value = value; this.left = null; this.right = null; }
} class BinaryTree { constructor() { this.root = null; } insert(value) { let newNode = new TreeNode(value); if (!this.root) { this.root = newNode; } else { this.insertNode(this.root