JavaScript链表
时间: 2023-02-06 08:37:42 浏览: 108
JavaScript 中的链表是一种特殊的数据结构,其中的每个元素都包含一个值和一个指向下一个元素的指针。这种数据结构具有许多优点,例如插入和删除元素时间复杂度较低,对于需要快速插入或删除元素的应用特别有用。但是,链表相对于数组,访问某个元素的时间复杂度要高,因为需要遍历整个链表才能找到所需的元素。
JavaScript 中的链表通常由一个带有指向链表中第一个元素的指针的对象来表示。每个元素都是一个带有值和指向下一个元素的指针的对象。最后一个元素的指针通常指向 null,表示链表的结尾。
下面是一个简单的 JavaScript 链表的例子:
```
function LinkedList() {
this.head = null;
this.tail = null;
}
function Node(value, next, prev) {
this.value = value;
this.next = next;
this.prev = prev;
}
LinkedList.prototype.addToHead = function(value) {
const newNode = new Node(value, this.head, null);
if (this.head) this.head.prev = newNode;
else this.tail = newNode;
this.head = newNode;
};
LinkedList.prototype.addToTail = function(value) {
const newNode = new Node(value, null, this.tail);
if (this.tail) this.tail.next = newNode;
else this.head = newNode;
this.tail = newNode;
};
LinkedList.prototype.removeHead = function() {
if (!this.head) return null;
let value = this.head.value;
this.head = this.