29
Arrays and linked lists
Inserting into the middle of a list
Suppose you want your todo list to work more like a calendar. Earlier,
you were adding things to the end of the list.
Now you want to add them in the order in which they should
be done.
What’s better if you want to insert elements in the middle: arrays or
lists? With lists, it’s as easy as changing
what the previous element
points to.
But for arrays, you have to shift all the rest of the elements down.
And if there’s no space, you might have to copy everything to a new
location! Lists are better if you want to insert elements into the middle.
Unordered
Ordered
30
Chapter 2
I
Selection sort
Deletions
What if you want to delete an element? Again,
lists are better, because
you just need to change what the previous element points to. With
arrays, everything needs to be moved up when you delete an element.
Unlike insertions, deletions will always work. Insertions can fail
sometimes when there’s no space left in memory. But you can always
delete an element.
Here are the run times for common
operations on arrays and
linked lists.
It’s worth mentioning that insertions and deletions are O(1) time only
if you can instantly access the element to be deleted. It’s a common
practice to keep track of the first and last items in a linked list, so it
would take only O(1) time to delete those.
Which are used more: arrays or lists? Obviously,
it depends on the use
case. But arrays see a lot of use because they allow random access. There
are two different types of access:
random access
and
sequential access
.
Sequential access means reading the elements one by one, starting
at the first element.
Linked lists can
only
do sequential access. If you
want to read the 10th element of a linked list, you have to read the first
9 elements and follow the links to the 10th element. Random
access
means you can jump directly to the 10th element. You’ll frequently
hear me say that arrays are faster at reads. This is because they provide
random access. A lot of use cases require random access,
so arrays are
used a lot. Arrays and lists are used to implement other data structures,
too (coming up later in the book).