What is your hint or solution suggestion?
Solution
this.addAt = function(index, element) {
let node = new Node(element);
// check for negative values and values beyond current length of LinkedList
if (index < 0 || index > length) {
return false;
}
// inserting to end of list reuses functionality
if (index === length) {
this.add(element);
} else {
let count = 0;
let previousNode = head;
// insert at head of the list shift the reference of the head and the new node
if (index === count) {
head = node;
node.next = previousNode;
length++;
return true;
}
while(previousNode) {
let currentNode = previousNode.next;
count++;
// inserting at value in between nodes shifts reference of the previousNode and the new nodes next to the currentNode
if (currentNode) {
if (count === index) {
previousNode.next = node;
node.next = currentNode;
length++;
return true;
}
}
previousNode = currentNode;
}
}
}
Challenge: Add Elements at a Specific Index in a Linked List
Link to the challenge: