返回
JS实现的链表:一行代码搞定,再也不用因没有链表而苦恼!
前端
2023-12-05 22:51:03
一、链表简介
链表是一种线性的数据结构,由一系列被称为“节点”的元素组成。每个节点包含一个值和指向下一个节点的指针。链表的主要优点是易于插入和删除节点,而无需移动其他节点。
二、在 JavaScript 中实现链表
令人惊讶的是,JavaScript 并没有内置的链表数据结构。但是,我们可以使用一行代码轻松实现一个链表。
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
append(value) {
const newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
prepend(value) {
const newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
}
insertAfter(value, afterValue) {
const newNode = new Node(value);
let currentNode = this.head;
while (currentNode) {
if (currentNode.value === afterValue) {
newNode.next = currentNode.next;
currentNode.next = newNode;
if (currentNode === this.tail) {
this.tail = newNode;
}
return;
}
currentNode = currentNode.next;
}
throw new Error("Value not found in the list.");
}
delete(value) {
if (this.head === null) {
return;
}
if (this.head.value === value) {
this.head = this.head.next;
if (this.head === null) {
this.tail = null;
}
return;
}
let currentNode = this.head;
let previousNode = null;
while (currentNode) {
if (currentNode.value === value) {
previousNode.next = currentNode.next;
if (currentNode === this.tail) {
this.tail = previousNode;
}
return;
}
previousNode = currentNode;
currentNode = currentNode.next;
}
throw new Error("Value not found in the list.");
}
print() {
let currentNode = this.head;
while (currentNode) {
console.log(currentNode.value);
currentNode = currentNode.next;
}
}
}
三、使用示例
以下是一些使用链表的示例:
- 存储用户数据: 链表可以用于存储用户数据,例如用户名、密码和电子邮件地址。
- 实现队列: 链表可以轻松实现队列,队列是一种遵循先进先出 (FIFO) 原则的数据结构。
- 实现栈: 链表也可以实现栈,栈是一种遵循后进先出 (LIFO) 原则的数据结构。
- 实现图: 链表可以用于实现图,图是一种数据结构,用于表示对象之间的关系。
四、结束语
总之,链表是一种重要的数据结构,即使JavaScript中没有内置的链表,我们也可以使用一行代码轻松实现一个链表。希望本文对您有所帮助。