JavaScript链表需手动实现,核心是用对象模拟节点并通过next指针串联;所有操作(访问、修改、插入、删除)必须从头节点遍历,无法随机访问。
JavaScript 中链表不是内置数据结构,需要手动实现。核心是用对象模拟节点,通过 next(和可选的 prev)指针串联。操作节点数据的关键在于:**访问、修改、插入、删除都必须从头节点出发,沿指针逐个遍历,不能像数组那样随机访问。**
每个节点是一个包含数据和指向下一节点引用的对象:
class ListNode {
constructor(data) {
this.data = data;
this.next = null; // 指向下一个节点
}
}
链表本身通常只保存头节点(head),它是入口点:
class LinkedList {
constructor() {
this.head = null;
}
}
空链表即 this.head === null;只要头节点存在,就能顺着 next 一路访问后续所有节点。
必须从头开始遍历,找到目标位置或满足条件的节点后,才能读或写 node.data:
getNodeDataAt(index) {
let current = this.head;
let count = 0;
while (current !== null && count < index) {
current = current.next;
count++;
}
return current ? current.data : undefined;
}
setNodeDataAt(index, newData) {
let current = this.head;
let count = 0;
while (current !== null && count < index) {
current = current.next;
count++;
}
if (current) current.data = newData;
}
updateFirstMatch(oldValue, newValue) {
let current = this.head;
while (current !== null) {
if (current.data === oldValue) {
current.data = newValue;
return true;
}
current = current.next;
}
return false;
}
插入/删除会改变节点之间的连接关系,进而影响后续遍历顺序和数据可见性:
prepend(data) {
const newNode = new ListNode(data);
newNode.next = this.head;
this.head = newNode;
}
append(data) {
const newNode = new ListNode(data);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = newNode;
}
target 的第一个节点:
deleteByValue(target) {
if (!this.head) return;
if (this.head.data === target) {
this.head = this.head.next;
return;
}
let current = this.head;
while (current.next && current.next.data !== target) {
current = current.next;
}
if (current.next) {
current.next = current.next.next;
}
}
实际开发中常需对所有节点数据做统一处理,比如打印、求和、过滤:
traverse(callback) {
let current = this.head;
while (current !== null) {
callback(current.data);
current = current.next;
}
}
// 使用示例:打印所有数据
list.traverse(data => console.log(data));
toArray() {
const arr = [];
let current = this.head;
while (current !== null) {
arr.push(current.data);
current = current.next;
}
return arr;
}
findAllByCondition(predicate) {
const result = [];
let current = this.head;
while (current !== null) {
if (predicate(current.data)) {
result.push(current.data);
}
current = current.next;
}
return result;
}
// 使用示例:找出所有大于 10 的数
const bigNumbers = list.findAllByCondition(x => x > 10);
链表的操作本质是“指针重连”,数据存于节点内,增删改查都依赖对 next 引用的正确操作。熟练掌握遍历模式,就能稳定地操作任意节点的数据。不复杂但容易忽略边界——比如空链表、单节点、删头节点等场景,写逻辑时多检查 current 是否为 nu 就能避免报错。
ll