我的问题是关于当 head.value === valueToDelete 时,根据传递到删除节点函数的值删除作为头的节点的操作。我们将简单地将 head 声明为下一个值。
在Javascript中,失去了列表中链接并且不再是头(在内存中等)的旧头会发生什么?也不介意其他类型更严格的语言的崩溃。预先感谢您帮助我理解。
var LinkedList = function () {
this.head = null;
this.tail = null;
};
LinkedList.prototype.makeNode = function (val) {
var node = {};
node.val = val;
node.next = null;
return node;
};
LinkedList.prototype.deleteFromAnywhere = function (valueToDelete) {
var current = this.head;
var previous = current;
//from head:
if (current.val === valueToDelete || valueToDelete === this.head.val) {
this.head = current.next;
}
//from middle:
while (current.next) {
if (current.val === valueToDelete) {
//drop the link of the deleted, point the one before it to the one after it
previous.next = current.next;
}
//from tail:
if (current.val === valueToDelete && (current.next === null || this.tail.val === valueToDelete)) {
this.tail = previous;
previous.next = null;
}
//increment, keep previous one behind/current one ahead.
//ie skip ahead.
previous = current;
current = current.next;
}
};
LinkedList.prototype.addToTail = function (value) {
var newTail = this.makeNode(value);
if (!this.head) {
this.head = newTail;
}
if (this.tail) {
this.tail.next = newTail;
}
this.tail = newTail;
};
var list = new LinkedList();
list.addToTail(4);
list.addToTail(5);
list.addToTail(8);
list.deleteFromAnywhere(5);
console.log(list);