返回
6分钟让你精通双向链表:从零到精通JavaScript实现
前端
2023-10-25 11:39:44
双向链表入门
在计算机科学中,双向链表是一种存储元素并允许按顺序访问它的数据结构。每个元素都包含一个值和两个指针,分别指向链表中的前一个和后一个元素。
JavaScript实现
创建双向链表
class Node {
constructor(value) {
this.value = value;
this.next = null;
this.prev = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
}
增添元素
append(value) {
const newNode = new Node(value);
if (this.length === 0) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
this.length++;
return this;
}
prepend(value) {
const newNode = new Node(value);
if (this.length === 0) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
}
this.length++;
return this;
}
insert(position, value) {
if (position < 0 || position > this.length) {
throw new Error("Invalid position");
}
if (position === 0) {
return this.prepend(value);
}
if (position === this.length) {
return this.append(value);
}
const newNode = new Node(value);
const prevNode = this.getNodeAt(position - 1);
const nextNode = prevNode.next;
prevNode.next = newNode;
newNode.prev = prevNode;
newNode.next = nextNode;
nextNode.prev = newNode;
this.length++;
return this;
}
删除元素
removeAt(position) {
if (position < 0 || position >= this.length) {
throw new Error("Invalid position");
}
if (position === 0) {
return this.removeHead();
}
if (position === this.length - 1) {
return this.removeTail();
}
const prevNode = this.getNodeAt(position - 1);
const nodeToRemove = prevNode.next;
const nextNode = nodeToRemove.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
this.length--;
return nodeToRemove;
}
其他方法
find(value) {
let currentNode = this.head;
while (currentNode !== null) {
if (currentNode.value === value) {
return currentNode;
}
currentNode = currentNode.next;
}
return null;
}
reverse() {
let currentNode = this.tail;
this.head = currentNode;
this.tail = this.head.prev;
while (currentNode !== null) {
const nextNode = currentNode.prev;
currentNode.prev = currentNode.next;
currentNode.next = nextNode;
currentNode = nextNode;
}
}
总结
双向链表是JavaScript中一种常见的数据结构,具有广泛的应用。希望这篇教程能帮助您更好地理解双向链表并应用它们来构建更强大的应用程序。