js 链表实现
链表基础概念
链表是一种线性数据结构,由一系列节点组成,每个节点包含数据部分和指向下一个节点的指针。与数组不同,链表的内存分配不要求连续,插入和删除操作效率更高。
单向链表实现
以下是单向链表的基本实现代码示例:

class ListNode {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// 添加节点到链表末尾
add(data) {
const node = new ListNode(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 ListNode(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++;
}
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 = null;
let i = 0;
while (i < index) {
prev = current;
current = current.next;
i++;
}
removedNode = current;
prev.next = current.next;
}
this.size--;
return removedNode.data;
}
}
双向链表实现
双向链表每个节点包含指向前后节点的指针:

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;
}
// 添加到末尾
add(data) {
const node = new DoublyListNode(data);
if (!this.head) {
this.head = node;
this.tail = node;
} else {
node.prev = this.tail;
this.tail.next = node;
this.tail = node;
}
this.size++;
}
}
链表常用操作
打印链表内容:
printList() {
let current = this.head;
let str = "";
while (current) {
str += current.data + " -> ";
current = current.next;
}
console.log(str + "null");
}
反转链表:
reverse() {
let current = this.head;
let prev = null;
let next = null;
while (current) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
this.head = prev;
}
性能特点
链表在插入和删除操作时时间复杂度为O(1)(已知位置情况下),而访问元素需要O(n)时间。适合频繁增删但随机访问较少的场景。






