re: thank u, next: an introduction to linked lists VIEW POST

FULL DISCUSSION
 

Shouldn't there be a method to remove a given index?

 

It’s incredibly similar to the remove value!

 
remove_value(value) {
    while (this.head && this.head === value) { // Special-casing the head
        this.head = this.head.next
    }

    for (let node = this.head; node.next; node = node.next) {
        while (node.next === value) {
            node.next = node.next.next
        }
    }
}

remove(i) {
    if (i === 0) { // Still special-casing the head. If only JS had pointers...
        this.head = null
        return
    }

    let node = this.head

    for (var j = 0; j++; j < i - 1) { // Go just *before* the node we need
        node = node.next
    }

    node.next = null
    this.length--
}
code of conduct - report abuse