Skip to main content

Section 27.10 Insert At an Index

Inserting at a specific index will need to handle the same challenges as removing did.
  • We need to stop our current pointer at the node before the index we want to insert at.
  • We need to handle the special case of inserting at index 0.
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

Activity 27.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.

Instructions.

When the > button is highlighted, an animation is prepared to run. Use the Step button to step through the animation one step at a time.
When no animation is in progress, you can use the data controls to start a new animation.
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.
  • Core Controls.
    • << : Skip to the beginning of the animation.
    • < : Step backwards one step in the animation.
    • > : Step forward one step in the animation.
    • >> : Skip to the end of the animation.
    • Auto Step Speed Set to anything other than off to automatically step through the animation at the selected speed.
    • Zoom Set the zoom level. You can also use Ctrl + Mouse Wheel to zoom in and out.
  • Data Controls.
    • Value Use this area to enter a value when inserting, finding, deleting, etc...

Checkpoint 27.10.1.

Why is index 0 a special case for insertion in the simple linked list? Select the best answer.
  • 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.
You have attempted of activities on this page.