Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the removeAt() function remove the removing node’s pointer?

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?

like image 706
user17922661 Avatar asked Feb 27 '26 10:02

user17922661


1 Answers

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.

like image 196
trincot Avatar answered Feb 28 '26 22:02

trincot