8.5. Linked List Get Operation¶
In this section, we will take a closer look at the get(int index)
operation with a linked list implementation.
The main drawback of a linked list implementation is that elements are
slower to access. Each access requires the program to traverse from the
head of the list to the desired index. The images below demonstrate how
this might be accomplished if the instruction myList.get(2)
is
executed.
A reference,
temp
, is assigned to thehead
of the list (index 0).We move
temp
to the next node in the list. Now,temp
is located at index 1. We avoid modifyinghead
as to not change the list itself. If we were to lose thehead
reference, we would lose access to the first node in the list.We move
temp
to the next node in the list. Now,temp
is located at index 2, which is our desired destination. At this point, we can returnvalue
from theNode
object referenced bytemp
as that is the value we want.
Compare this method to arrays where we would simply return array[2]
.
With an array implementation, the program can directly access the
requested index (one of the benefits of arrays). Traversing the links in
a linked list implementation is more costly. Especially when the desired
element is located toward the end of a long linked list.