链表 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 current = this.head;
if (index === 0) {
this.head = current.next;
} else {
let prev = null;
let i = 0;
while (i < index) {
prev = current;
current = current.next;
i++;
}
prev.next = current.next;
}
this.size--;
return current.data;
}
// 获取节点数据
getData(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(" -> "));
}
}
双向链表的实现
双向链表的节点包含指向前一个和后一个节点的指针,以下是实现代码:

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++;
}
// 在头部添加节点
prepend(data) {
const newNode = new DoublyListNode(data);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
}
this.size++;
}
// 删除指定位置的节点
removeAt(index) {
if (index < 0 || index >= this.size) return null;
let current = this.head;
if (index === 0) {
this.head = current.next;
if (this.head) this.head.prev = null;
else this.tail = null;
} else if (index === this.size - 1) {
current = this.tail;
this.tail = current.prev;
this.tail.next = null;
} else {
let i = 0;
while (i < index) {
current = current.next;
i++;
}
current.prev.next = current.next;
current.next.prev = current.prev;
}
this.size--;
return current.data;
}
}
链表的常见操作
- 查找节点:遍历链表直到找到目标数据或到达末尾。
- 反转链表:通过迭代或递归方式反转链表节点的指向。
- 检测环:使用快慢指针(Floyd 算法)判断链表是否有环。
应用场景
链表适合动态数据管理,如实现队列、栈、哈希表的链地址法等场景。其优势在于高效的插入和删除操作,但随机访问效率较低。






