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
let deletedNode = head;
if (index == 0) {
head = null;
} else {
let currentNode = head;
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 previousNode = head;
let currentNode = head.next;
let currentIndex = 1;
if (index === 0) {
head = length === 1 ? null : head.next;
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