gpt4 book ai didi

javascript - removeAt() 函数是否应该删除删除节点的指针?

转载 作者:行者123 更新时间:2023-12-05 04:37:40 25 4
gpt4 key购买 nike

我是编码初学者,最近在研究 JavaScript 上的链表。

我很困惑,在删除节点时,我是否也应该将删除节点的指针更改为null

RemoveAt(index) 方法是一种自定义方法,用于删除特定索引处的节点。

示例如下:

// remove node 
removeAt(index){
// check if index is qualified
if(index < 0 || index > this.length) return null;
let current = this.head,
prev = null,
idx = 0;
// if first node
if(index===0){
// point the head to next node
this.head = current.next;
}else{
// else find the index
while(idx++ < index){
prev = current; // set prev node as current
current = current.next; // and move current to the next node
}
// index finded, link prev.next & current.next
prev.next = current.next;
}
this.length--;
}

我在JS中看到的大部分链表例子都省略了这个。我想知道它会不会浪费更多内存?

最佳答案

您不需要分配 nullcurrent .它是函数的局部变量,因此一旦函数退出,就不再有对已删除节点的引用,并且可以进行垃圾回收。

如果在函数上下文之外您碰巧有另一个对已删除节点的引用,则该节点将不会被垃圾回收。正在分配 nullcurrent不会改变这种情况。

一些编码人员可能希望隔离节点但是:

current.next = null;

这样,如果某处仍然有对该节点的引用,则没有从该节点进入列表的风险,这可能是不希望的。另一方面,如果在函数外部仍然存在对已删除节点的引用,那确实是一种代码味道,如果该引用仍用于遍历其 next,它会变得非常难闻。属性(property)。所以如果整个代码都在做正确的事情,你真的不需要做 current.next = null要么。

关于javascript - removeAt() 函数是否应该删除删除节点的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70693792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com