从链表中删除链表头部节点时出现悬空节点

问题描述 投票:0回答:1

我的问题是关于当 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);

javascript linked-list
1个回答
0
投票

不再引用的对象可用于垃圾收集

有一个垃圾收集器时不时地运行并释放相关的内存。这与严格/丢失打字无关。严格类型的Java也有这样的垃圾收集器

© www.soinside.com 2019 - 2024. All rights reserved.