Is this doubly linked list method, correct? (Remove)

Viewed 30
remove(range){
    if(range === 0){
        return this.shift();
    }
    else if(range == this.length){
        return this.pop();
    }
    else if(range < 0 || range > this.length ){
        return undefined
    }
    else{
        const temp = this.get(range);
        const after = temp.next;
        const before = temp.prev;
        before.next = after;
        after.prev = before;
        temp.next = null;
        temp.prev = null;
        this.length--;
        return temp;
        
    }
}

I wrote this method for remove in a doubly linked list, it works, but I'm not sure if it's correct overall.

1 Answers

There is essentially one issue:

The index of the last node in a linked list is not this.length but this.length - 1. For example, if a linked list has two nodes, its length is 2, and the nodes have indices 0 and 1.

So this part of the code:

    else if(range == this.length){
        return this.pop();
    }
    else if(range < 0 || range > this.length ){
        return undefined
    }

Should be changed to:

    else if(range == this.length - 1){
//                              ^^^^
        return this.pop();
    }
    else if(range < 0 || range >= this.length ){
//                             ^^
        return undefined
    }

Not a problem, but the name range is not well chosen as it suggests a pair:

For example, the range of a signed 16-bit integer variable is all the integers from −32,768 to +32,767.

As in your case this parameter is a single integer denoting the 0-based position of the targeted node, the name index should be preferred.

Related