# Solution for "Remove Elements from a Linked List"

Continuing the discussion from freeCodeCamp Challenge Guide: Remove Elements from a Linked List by Index:

Hey! Can someone correct me if I am wrong, but won’t the solution listed disconnect the rest of the list, if there is more than one element but the index being searched for is 0, essentially bringing the length to 0? Maybe I am missing something.

Here is the solution listed:

this.removeAt = function(index) {
// Exit early on bad input
if (index < 0 || index >= length) {
return null;
}

// Find deleted node and remove
if (index == 0) {
} else {
let currentIndex = 0;
while (currentIndex < index - 1) {
currentNode = currentNode.next;
currentIndex++;
}
deletedNode      = currentNode.next;
currentNode.next = deletedNode.next;
}

// Update and return
length--;
return deletedNode.element;
}

I was thinking something like this may work better:

this.removeAt = index => {
if (index < 0 || index >= length) return null;
let currentIndex = 1;
if (index === 0) {
length--;
return previousNode;
} else {
while (currentIndex !== index) {
previousNode = currentNode;
currentNode = currentNode.next;
currentIndex++;
}
previousNode.next = currentNode.next;
length--;
return currentNode.element;
}
}

Any thoughts would be appreciated. Sorry if I formatted anything wrong in this post, or this is the wrong section to post. Second time posting anything

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.