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