8.8. Linked List Add Operation¶
A linked list can grow by allocating a new node and updating links.
The snapshots below illustrate the steps needed for myList.add(2, "F")
in a list containing "A", "B", and "C". The list initially
has size 3, and index 2 is a valid insertion index.
Each snapshot shows the state after the described step is completed.
Construction of the initial list is hidden, and the models show only the
fields needed for this example. String values use a compact display:
each item field stores a reference value, and the corresponding
String object exists separately from the node. An arrow connects each string
reference box to a literal beside it.
Create a node whose
itemfield stores a reference to the string"F"and whosenextfield storesnull. Initializetempwith a copy of the reference value stored inmyList.head. Bothtempandheadrefer to the node at index 0, whose item is"A". The new node is not yet part of the list, so the size is still 3.Follow one link by copying the reference value in
temp.nextintotemp. Nowtemprefers to the node at index 1, whose item is"B". This is the node immediately before the insertion index. Reassigningtempleavesheadand all links unchanged.Copy the reference value in
temp.nextintonewNode.next. The new node now links to the node whose item is"C". The node whose item is"B"still links directly to that same node. Save this successor reference before replacingtemp.next; reversing these two assignments would make the new node link to itself and disconnect the original successor from the list.Copy the reference value in
newNodeintotemp.next, then increment the list's size. The node whose item is"B"now links to the new node, which links to the node whose item is"C". The list contains"A","B","F", and"C", in that order, and its size is 4. Itsheadstill refers to the first node.The final snapshot shows the same completed list without the traversal variables
tempandnewNode. No further link changes are needed. The new item is at index 2, and the item previously at index 2 is now at index 3; the existing nodes have not moved in memory.
This example inserts after an existing node. Inserting at index 0
requires updating head because there is no predecessor node.
Compare these steps to insertion in an array-based list. Finding the predecessor in a linked list requires traversal. Once that node is known, inserting the new node requires a fixed number of reference assignments and a size update, regardless of the list's length. An array-based list may need to shift items to make room even when its array has spare capacity. If the array is full, it also needs a larger array and must copy the existing items. The relative cost therefore depends on the insertion position and available capacity; neither implementation is always faster.