We can use the same kinds of logic to handle them. We will advance our current pointer index - 1 times. And, before we do that, we can check if the index is 0. If it is, we can call our existing insertStart method to handle the special case.
Once we are sure the index is not 0 and have advanced our current pointer to the node before the desired index, we can insert the new node. We will need to do something like the following:
ListNode* newNode = new ListNode(value); // Create the new node
newNode->next = current->next; // Point new node to the next node
current->next = newNode; // Point current to the new node
Activity27.10.1.Linked List Insert At.
The animation has already created a current pointer and advanced it once. Type 20 into the Value box. Then use Insert After Current to insert that value at index 2.
You can click and drag on the animation area to pan around. Use the Ctrl + mouse wheel (or touchpad scroll gesture) while over the animation area to zoom in and out.
Because the node at index 0 is tracked by the head pointer
Because it contains the first element
That does not directly explain why it is a special case for insertion.
Because index 0 means there are no nodes in the list
Index 0 can be a valid index in a non-empty list, so it is not necessarily the case that there are no nodes in the list when inserting at index 0.
Because inserting at index 0 requires shifting all the other nodes down one index
In a linked list, we do not need to shift any nodes when inserting at index 0. We just need to update the head pointer and the next pointer of the new node.