一、数组
1. 数组是什么?
数组是一种线性数据结构
const arr = \['A', 'B', 'C']; // 索引: 0 1 2
你可以通过索引 arr[1] 快速找到 B,就像“数格子”一样,访问非常快。
2. 数组的特点
| 操作 | 是否快 | 说明 |
|---|---|---|
| 访问元素 | ✅ 快(O(1)) | 通过下标直接访问 |
| 尾部添加/删除 | ✅ 快(O(1)) | push 和 pop 很高效 |
| 头部添加/删除 | ❌ 慢(O(n)) | 因为要移动所有元素 |
| 中间插入/删除 | ❌ 慢(O(n)) | 也需要移动元素 |
3. JS 常用数组方法
const arr = \[10, 20, 30];
arr.push(40); // 尾部添加
arr.pop(); // 尾部删除
arr.unshift(5); // 头部添加
arr.shift(); // 头部删除
arr.splice(1, 0, 15); // 在索引1位置插入15
二、栈
1. 栈是什么?
栈就像一个“叠盘子”的地方,后放进去的盘子先拿出来,这叫后进先出(LIFO)。
栈底 → \[1, 2, 3] ← 栈顶
入栈(push):往上放一个
出栈(pop):从上拿一个
2. 栈的 JS 实现
const stack = [];
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 2 出栈,先出的最后一个进的
3.括号匹配算法
function isValid(str) {
const stack = [];
const map = {
"(": ")",
"[": "]",
"{": "}",
};
for (let char of str) {
if (map[char]) {
stack.push(char);
} else {
const last = stack.pop();
if (map[last] !== char) {
return false;
}
}
}
return stack.length === 0;
}
三、队列(Queue)
1. 队列是什么?
就像你排队买东西一样:你先来你先买,先进先出(FIFO)。
队头 → \[1, 2, 3] ← 队尾
入队(enqueue)是从队尾进
出队(dequeue)是从队头出
2. 队列的 JS 实现(用数组模拟)
const queue = [];
queue.push(1); // 入队
queue.push(2);
console.log(queue.shift()); // 1 出队,先来的先出去
3.模拟最近浏览记录(只保留最近五条)
class RecentHistory {
constructor(limit = 5) {
this.queue = [];
this.limit = limit;
}
visit(page) {
if (this.queue.length >= this.limit) {
this.queue.shift(); //删除最早的
}
this.queue.push(page);
}
getHistory() {
return this.queue;
}
}
四、链表(Linked List)
1. 链表是什么?
链表由一个个“节点”组成,每个节点包含:
- 值(value)
- 指向下一个节点的“指针”(next)
不像数组连续排列,链表是“手拉手”的结构:
[1] → [2] → [3] → null
2. 单向链表 JS 实现
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
append(value) {
const node = new Node(value);
if (!this.head) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
}
print() {
let current = this.head;
while (current) {
console.log(current.value);
current = current.next;
}
}
}
const list = new LinkedList();
list.append(10);
list.append(20);
list.append(30);
list.print(); // 10 20 30
3. 链表的优势
- 插入删除快(只改指针)✅
- 访问慢(要从头找)❌
4.反转链表
function reverseList(head) {
let prev = null;
let current = head;
while (current) {
const next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
五、四种数据结构的对比
| 数据结构 | 特点 | 应用场景 |
|---|---|---|
| 数组 | 顺序存储,快速访问 | 排序、查找 |
| 栈 | 后进先出 | 括号匹配、函数调用栈 |
| 队列 | 先进先出 | 排队、任务调度 |
| 链表 | 快速插入删除 | 实现队列、LRU缓存等 |