链表用js实现
链表的基本概念
链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(或引用)。与数组不同,链表在内存中是非连续存储的,插入和删除操作更高效,但随机访问性能较差。

单链表的实现
以下是单链表的 JavaScript 实现,包含常用操作(插入、删除、查找等):
class ListNode {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// 在链表末尾添加节点
append(data) {
const newNode = new ListNode(data);
if (!this.head) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
this.size++;
}
// 在指定位置插入节点
insertAt(data, index) {
if (index < 0 || index > this.size) return false;
const newNode = new ListNode(data);
if (index === 0) {
newNode.next = this.head;
this.head = newNode;
} else {
let current = this.head;
let prev = null;
let i = 0;
while (i < index) {
prev = current;
current = current.next;
i++;
}
newNode.next = current;
prev.next = newNode;
}
this.size++;
return true;
}
// 删除指定位置的节点
removeAt(index) {
if (index < 0 || index >= this.size) return null;
let removedNode;
if (index === 0) {
removedNode = this.head;
this.head = this.head.next;
} else {
let current = this.head;
let prev = null;
let i = 0;
while (i < index) {
prev = current;
current = current.next;
i++;
}
removedNode = current;
prev.next = current.next;
}
this.size--;
return removedNode.data;
}
// 查找节点数据
getAt(index) {
if (index < 0 || index >= this.size) return null;
let current = this.head;
let i = 0;
while (i < index) {
current = current.next;
i++;
}
return current.data;
}
// 打印链表数据
print() {
let current = this.head;
const result = [];
while (current) {
result.push(current.data);
current = current.next;
}
console.log(result.join(" -> "));
}
}
使用示例
const list = new LinkedList();
list.append(10);
list.append(20);
list.append(30);
list.insertAt(15, 1);
list.print(); // 输出: 10 -> 15 -> 20 -> 30
list.removeAt(2);
list.print(); // 输出: 10 -> 15 -> 30
console.log(list.getAt(1)); // 输出: 15
双向链表的实现
双向链表的节点包含指向前驱和后继的指针,以下是一个简单实现:
class DoublyListNode {
constructor(data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
// 在末尾添加节点
append(data) {
const newNode = new DoublyListNode(data);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.prev = this.tail;
this.tail.next = newNode;
this.tail = newNode;
}
this.size++;
}
}
注意事项
- 链表操作的时间复杂度:
- 插入/删除(已知位置):O(1)(双向链表)或 O(n)(单链表需遍历)。
- 查找:O(n)。
- 适用场景:频繁插入/删除且无需随机访问的场景(如实现队列、LRU 缓存等)。







