[JS与链表]双向链表
warning:
这篇文章距离上次修改已过185天,其中的内容可能已经有所变动。
class DoublyLinkedListNode {
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 DoublyLinkedListNode(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;
}
delete(value) {
if (this.length === 0) return null;
let current = this.head;
while (current.value !== value) {
if (current.next === null) return null;
current = current.next;
}
if (current === this.head) {
if (this.length === 1) {
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
this.head.prev = null;
current.next = null;
}
} else if (current === this.tail) {
this.tail = current.prev;
this.tail.next = null;
current.prev = null;
} else {
current.prev.next = current.next;
current.next.prev = current.prev;
current.next = null;
current.prev = null;
}
this.length--;
return current.value;
}
}
这段代码实现了一个简单的双向链表,包含了添加节点和删除节点的基本操作。添加节点时,如果链表为空,则新节点既是头节点也是尾节点;如果不为空,则新节点成为尾节点,并且其前驱指向当前的尾节点。删除节点时,需要考虑节点位于头部、尾部还是中间的不同情况,并更新相关节点的prev和next指针。
评论已关闭