JavaScript 中的双向链表
在本文中,我们将讨论 JavaScript 中的双向链表类数据结构。这是一种线型数据结构。在所有操作中,双向链表几乎与单链表相同,我们只需为每个节点再跟踪一个额外的链接即可。在单链表中,我们只有 next 链接,在双向链表中,我们有 2 个链接:next 和 prev。
双向链表表示为 −
请注意,在类本身中,我们还需要跟踪尾部(最后一个元素)。
示例
在此示例中,我们了解双向链表及其在 JavaScript 中的操作的实现。在这里,我们在向其中插入数据时创建链表;并在从中删除数据时可能删除节点。我们还使用用户定义方法 print() 来打印链表。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Doubly Linked List Data Structure</title>
</head>
<body>
<script type="text/javascript">
function createNode(value) {
return {
value: value,
next: null,
previous: null,
};
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
insert(value) {
this.size++;
let newNode = createNode(value);
if (this.tail) {
this.tail.next = newNode;
newNode.previous = this.tail;
this.tail = newNode;
return newNode;
}
this.head = this.tail = newNode;
return newNode;
}
remove() {
if (this.tail) {
this.size--;
let removedTail = this.tail;
let beforeTail = this.tail.previous;
this.tail = beforeTail;
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
return removedTail;
}
return undefined;
}
print() {
document.write("The Elements in the Doubly Linked List are :</br> ");
let current = this.head;
while (current) {
document.write(
`${current.previous?.value} ${current.value} ${current.next?.value}`
);
current = current.next;
}
}
insertHead(value) {
this.size++;
let newNode = createNode(value);
if (this.head) {
this.head.previous = newNode;
newNode.next = this.head;
this.head = newNode;
return newNode;
}
this.head = this.tail = newNode;
return newNode;
}
insertIndex(value, index) {
if (index >= this.size) {
throw new Error("Insert index out of bounds");
}
if (index === 0) {
return this.insertHead(value);
}
this.size++;
let currentNode = this.head;
for (let i = 0; i < index; i++) {
currentNode = currentNode.next;
}
let previousNode = currentNode.previous;
let newNode = createNode(value);
newNode.next = currentNode;
newNode.previous = previousNode;
previousNode.next = newNode;
currentNode.previous = newNode;
return newNode;
}
}
let dLinkedList = new DoublyLinkedList();
dLinkedList.insert(7);
dLinkedList.insert(8);
dLinkedList.insert(9);
dLinkedList.print();
</script>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP