8.6. Linked List Add Operation¶
The main benefit of a linked list implementation is the fact that these
structures can easily increase size by adding a new, dynamically
allocated node object. The images below demonstrate how this might be
accomplished if the instruction myList.add(2, "F") is executed.
The method starts off by creating a
Nodeobject referenced bynewNodecontaining theStringto be added. Also, in this step, a temporary reference,temp, refers to the first node in the List.
We move
tempto the next node in the list. Now,tempis located at index 1. We avoid modifyingheadas to not change the list itself. If we were to lose theheadreference, we would lose access to the first node in the list.
Now that
tempis located at the index directly preceding where we want to add, we can start modifying the references to correctly addnewNodeto our list. In this step, we set thenextreference ofnewNodeto thenextvalue oftemp.
In this step, the
nextfield of the object referenced bytempis set tonewNode.
This image represents the same structure as the previous image just redrawn without any local variables with the nodes lined up cleanly.
Compare the above steps to the array list add operation. When there is space in the array for the new item, the linked list is much slower, comparatively. However, if there is not enough space in the array for the new item, then the linked list add operation is usually much faster! This is because it avoids the creation of a new array object and the loop required to transfer the contents from the old array to the new one.