学完这篇,你能不看资料手写出栈、队列、链表三个数据结构,并说清每个操作的时间复杂度、什么时候该用数组、什么时候该换链表。
这三种结构是所有算法的地基:浏览器前进后退是栈,消息队列、任务调度是队列,LRU 缓存、React Fiber 树用的是链表。手写一遍,比背十遍概念管用。下面用最朴素的 JS 类实现,每段都能直接丢进浏览器控制台跑。
第一步:栈,后进先出
栈只有一个口,进和出都在同一端。用数组实现最简单,push / pop 都是尾部操作,时间复杂度 O(1)。
class Stack {
#items = []; // 私有字段,外部拿不到内部数组
push(x) { this.#items.push(x); return this; }
pop() { return this.#items.pop(); } // 空栈返回 undefined
peek() { return this.#items[this.#items.length - 1]; }
get size() { return this.#items.length; }
get isEmpty() { return this.#items.length === 0; }
}
const s = new Stack();
s.push(1).push(2).push(3);
console.log(s.pop(), s.peek(), s.size); // 3 2 2
栈的经典用途:括号匹配、表达式求值、撤销操作、DFS 的非递归写法。判断括号是否合法,就是「遇左括号入栈,遇右括号比对栈顶」。
注意:别用 unshift / shift 去实现栈的头部进出,这两个方法每次都要搬动整个数组,复杂度是 O(n),数据量一大就明显卡。
第二步:队列,先进先出
一头进一头出。用数组的 push + shift 写起来最省事,但 shift 每次出队都要把后面所有元素往前挪一位,是 O(n)。正确做法是用对象存元素,加头尾两个指针:
class Queue {
#items = {};
#head = 0;
#tail = 0;
enqueue(x) { this.#items[this.#tail++] = x; return this; }
dequeue() {
if (this.isEmpty) return undefined;
const v = this.#items[this.#head];
delete this.#items[this.#head]; // 及时删除,防止对象无限膨胀
this.#head++;
return v;
}
get front() { return this.#items[this.#head]; }
get size() { return this.#tail - this.#head; }
get isEmpty() { return this.#tail === this.#head; }
}
出队只移动 #head 指针,不碰其他元素,入队出队都是 O(1)。当 #head 涨得很大时,可以在队列空了之后把两个指针重置为 0,避免对象 key 越来越多。
注意:对象的 key 会被转成字符串,这里靠 #head / #tail 两个数字保证连续递增,不要手动去删中间的 key,否则 size 计算就错了。
第三步:链表,插入删除不搬家
链表每个节点存「值 + 下一个节点」。优势是已知位置时插入删除只改指针,代价是不能像数组那样按下标随机访问。先写节点和单链表:
class Node {
constructor(value) { this.value = value; this.next = null; }
}
class LinkedList {
#head = null;
#size = 0;
append(value) { // 尾部追加
const node = new Node(value);
if (!this.#head) { this.#head = node; }
else {
let cur = this.#head;
while (cur.next) cur = cur.next;
cur.next = node;
}
this.#size++;
return this;
}
prepend(value) { // 头部插入,O(1)
const node = new Node(value);
node.next = this.#head;
this.#head = node;
this.#size++;
return this;
}
remove(value) { // 删除第一个匹配项
if (!this.#head) return false;
if (this.#head.value === value) { // 单独处理头节点
this.#head = this.#head.next;
this.#size--;
return true;
}
let prev = this.#head;
while (prev.next && prev.next.value !== value) prev = prev.next;
if (!prev.next) return false;
prev.next = prev.next.next;
this.#size--;
return true;
}
find(value) {
let cur = this.#head;
while (cur) { if (cur.value === value) return cur; cur = cur.next; }
return null;
}
toArray() {
const out = []; let cur = this.#head;
while (cur) { out.push(cur.value); cur = cur.next; }
return out;
}
get size() { return this.#size; }
}
append 每次都从头遍历到尾,是 O(n)。如果业务里频繁尾部追加,就再存一个 #tail 指针,追加变成 O(1);需要反向遍历或频繁删尾部,则升级成双向链表,节点多加一个 prev。
注意:删除节点时最容易漏掉「删除的是头节点」这一支。头节点没有前驱,必须单独改 #head,否则会删不掉或者丢掉整条链。
第四步:跑一遍验证
写完别急着收工,用一组用例把边界情况走一遍——空结构、单元素、删除不存在元素:
const list = new LinkedList();
list.append('a').append('b').append('c').prepend('head');
console.log(list.toArray()); // ['head','a','b','c']
console.log(list.remove('head'), list.toArray()); // true ['a','b','c']
console.log(list.remove('zzz')); // false
console.log(new Stack().pop(), new Queue().dequeue()); // undefined undefined
三个结构都遵循同一套套路:内部状态私有、对外只暴露有限方法、每个方法都考虑空结构的情况。这套写法迁移到集合、字典、树也是一样的。
小结
- 栈:
push / pop 都在尾部,数组实现即可,O(1);别用 shift / unshift。
- 队列:数组
shift 是 O(n),用「对象 + 头尾指针」实现 O(1) 出队,出队后记得删掉旧 key。
- 链表:插入删除只改指针,但访问是 O(n);删除时单独处理头节点,频繁尾插就加尾指针。
- 三个类都用
# 私有字段包住内部结构,外部只通过方法操作,避免被意外改坏。
- 写完必测空结构、单元素、找不到目标这三种边界,占 bug 来源的一大半。