I'm a beginner in coding and recently studying linked list on JavaScript.
I am confused that while removing node, should I also change the removing node’s pointer to null?
RemoveAt(index) method is a custom method for removing the node at a specific index.
Example as below:
// 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--;
}
Most of the linked list examples I saw in JS omitted this. I am wondering will it waste more memory?
You don't need to assign null to current. It is a variable that is local to the function, so as soon as the function exits, there is no more reference to the removed node, and it can be garbage collected.
If outside of the function's context you happen to have another reference to the node that is removed, then the node will not be garbage collected. Assigning null to current will not change that situation.
Some coders may want to isolate the node however:
current.next = null;
This way, if there is somewhere still a reference to that node, there is no risk of walking from that node into the list, which may be undesired. On the other hand, it really is a code smell if outside of the function there is still a reference to the node that is removed, and it would get really smelly if that reference is still used to traverse along its next property. So if the overall code is doing the right thing, you don't really need to do current.next = null either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With