DEV Community

Discussion on: thank u, next: an introduction to linked lists

Collapse
 
sollyucko profile image
Solomon Ucko
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--
}