An linked list is a data structure that implements a list. The elements are linked together by memory pointers. Unlike an array list, the elements of the list do not have to be stored in any particular order in memory.
In a linked list, each element of the list is stored in a cell, made up of two values:
Starting from the first cell in the list, you can read all the elements by moving from one cell to the next using the memory pointers. Here is the list:
[8, 7, 6, 5, 4]
The last cell in the list contains an null pointer (usually with a value 0) to show that there are no more elements. Notice that because each cell holds a pointer to the next, the cells can be stored anywhere in memory, there is no need for them to be stored next to each other like an array.
Suppose we wanted to add an element, value 3, at index 3, to make the list look like this:
[8, 7, 6, 3, 5, 4]
All the list needs to do is create a new cell with value 3. This can be created anywhere in memory.
The link between cells 3 and 4 is then broken. Cell 3 is altered to point at the new cell. The new cell points at the previous cell 4.
The list now contains 6 elements, in the correct order. The great thing is, there was no need to copy any elements. Al that needed to be done was to modify two memory pointers.
Going back to our original list, suppose we wanted to remove element 1 (value 7) to make the list look like this:
[8, 6, 5, 4]
All the list needs to do is change cell 0, so that instead of pointing to cell 1 it points to cell 2:
Now the list has 4 elements, in the correct order.
The cell containing value 7 is now no longer used. Its memory can be reclaimed to be used again.
A weak point of linked lists is that you cannot quickly find an element by index. Suppose you wanted to find the value at index 3. You would need to:
If there were thousands or millions of elements, this could take a while.
With a linked list, adding and removing elements is very fast. Looping through the elements in order is also very fast.
Finding an element by index can be slow.
Copyright (c) Axlesoft Ltd 2020