链表实现js
链表的基本概念
链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机访问效率较低。
单向链表的实现
以下是用JavaScript实现单向链表的核心代码:
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// 在链表尾部添加节点
add(data) {
const node = new Node(data);
if (!this.head) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
this.size++;
}
// 在指定位置插入节点
insertAt(data, index) {
if (index < 0 || index > this.size) return false;
const node = new Node(data);
if (index === 0) {
node.next = this.head;
this.head = node;
} else {
let current = this.head;
let prev;
for (let i = 0; i < index; i++) {
prev = current;
current = current.next;
}
node.next = current;
prev.next = node;
}
this.size++;
return true;
}
// 删除指定位置的节点
removeFrom(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;
for (let i = 0; i < index; i++) {
prev = current;
current = current.next;
}
removedNode = current;
prev.next = current.next;
}
this.size--;
return removedNode.data;
}
// 打印链表数据
print() {
let current = this.head;
let result = '';
while (current) {
result += `${current.data} -> `;
current = current.next;
}
console.log(result + 'null');
}
}
双向链表的实现
双向链表的节点包含前后两个指针,实现代码如下:
class DoublyNode {
constructor(data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
// 尾部添加节点
add(data) {
const node = new DoublyNode(data);
if (!this.head) {
this.head = node;
this.tail = node;
} else {
node.prev = this.tail;
this.tail.next = node;
this.tail = node;
}
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 {
for (let i = 0; i < index; i++) {
current = current.next;
}
current.prev.next = current.next;
current.next.prev = current.prev;
}
this.size--;
return current.data;
}
}
应用场景
- 动态内存分配:链表适合频繁插入和删除的场景,如操作系统内存管理。
- 实现高级数据结构:如栈、队列、图的邻接表等。
- 浏览器历史记录:双向链表可支持前进和后退功能。
性能对比
- 插入/删除:链表时间复杂度为O(1)(已知位置)或O(n)(需遍历),优于数组的O(n)。
- 随机访问:链表需遍历(O(n)),数组可直接索引(O(1))。
通过上述实现,可根据需求选择单向或双向链表。







