Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from singly linked list (javascript)

I'm doing a CodeFights problem, trying to remove elements from a singly linked list that has the value k.

Below is what I have (l is the list and k is the value):

function removeKFromList(l, k) {
    //figure out the head of the new list so we can reference it later
    var head = l;

    while (head.value === k){
        head = head.next;
    }

    var node = head;
    var temp = null;

    while (node && node !== null) {
        if (node.next.value === k){
            temp = node.next.next;
            node.next.next = null;
            node.next = temp;
        }
        node = node.next; 
        console.log("+++", head)
    }

    console.log("---", head)  
}

The CodeFight test cast is 3 -> 1 -> 2 -> 3 -> 4 -> 5. The final result would have been 1 -> 2 -> 4 -> 5. But my '---' console log keeps returning "Empty" (according to the CodeFights console).

My '+++' console log returns the correct head with element each loop.

I've been pulling my hair out over this, any idea what is missing here?

like image 577
Kaisin Li Avatar asked Jul 24 '26 07:07

Kaisin Li


1 Answers

You need to return the list if you delete the first node.

Then you need a loop for taking the next not while the value is not found.

At last you need a check if the last node exist and if the value is found, then assign the next node to the last next property.

function removeNode(list, value) {
    var node = list,
        last;

    if (node && node.value === value) {
        return node.next;
    }

    while (node && node.value !== value) {
        last = node,
        node = node.next;
    }
    if (last && node.value === value) {
        last.next = node.next;
    }
    return list;
}

var list = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: { value: 5, next: { value: 6, next: { value: 7, next: null } } } } } } };

list = removeNode(list, 5);
console.log(list)

list = removeNode(list, 1);
console.log(list)

list = removeNode(list, 7);
console.log(list)
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 133
Nina Scholz Avatar answered Jul 27 '26 03:07

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!