All pages 2 of 8
The linked list
A chain of notes, each saying where the next one is, so adding at the front is quick but reaching the end means walking.
Counted: 4 steps
The steps
- This note holds 4, not 3, so follow its arrow.
- This note holds 9, not 3, so follow its arrow.
- This note holds 3: found it.
- Point the arrow of 9 past 3, straight at 7.
- 3 is out of the list, in 4 steps.
What it is
Picture a treasure hunt. Each note tells you where to find the next one. You cannot skip ahead, because only the note before it knows where the next one is hidden.
A list kept this way is called a linked list. Each note is called a node. It holds a value and an arrow to the next node, called a link. The last arrow points nowhere.
How a move works
Adding at the front is quick. Write a new note, point its arrow at the old first note, and start the list there. That is 2 steps, however long the list is.
Finding a value means walking. In the list 4, 9, 3, 7, finding 9 takes 2 steps: read 4, then read 9.
Taking 3 out takes 4 steps. You read 4, 9 and 3 to find it. Then you move the arrow of 9 so it skips 3 and points straight at 7. Nothing else has to move. The list is now 4, 9, 7.
Where you meet it
A music player's list of songs, the undo trail in some apps and the pages behind a back button can all be linked lists. They shine when things are added and taken out often, since nothing has to shift along.
Watch out for
There is no drawer number. To reach the end, you must walk past every note. With eight notes, taking out the last one takes 9 steps: eight reads and one new arrow. So keep the things you need most near the front.