链表实现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 = null;
let i = 0;
while (i < index) {
prev = current;
current = current.next;
i++;
}
prev.next = node;
node.next = current;
}
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 = null;
let i = 0;
while (i < index) {
prev = current;
current = current.next;
i++;
}
prev.next = current.next;
removedNode = current;
}
this.size--;
return removedNode.data;
}
// 获取链表长度
getSize() {
return this.size;
}
// 打印链表内容
print() {
let current = this.head;
let str = '';
while (current) {
str += current.data + ' -> ';
current = current.next;
}
console.log(str + '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;
}
// 添加节点到末尾
append(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++;
}
// 在头部插入节点
prepend(data) {
const node = new DoublyNode(data);
if (!this.head) {
this.head = node;
this.tail = node;
} else {
node.next = this.head;
this.head.prev = node;
this.head = node;
}
this.size++;
}
}
循环链表的实现
循环链表最后一个节点指向头节点:
class CircularLinkedList {
constructor() {
this.head = null;
this.size = 0;
}
add(data) {
const node = new Node(data);
if (!this.head) {
this.head = node;
node.next = this.head;
} else {
let current = this.head;
while (current.next !== this.head) {
current = current.next;
}
current.next = node;
node.next = this.head;
}
this.size++;
}
}
链表操作的时间复杂度
- 访问:O(n)
- 搜索:O(n)
- 插入:O(1)(已知位置)
- 删除:O(1)(已知位置)
链表的应用场景
- 实现栈和队列
- 哈希表冲突处理
- 内存管理
- 实现图结构中的邻接表
以上实现展示了JavaScript中链表的基本操作,可以根据实际需求进行扩展和优化。






