Lesson 49: Follow the links
The route is in the pointers
- In a linked list each place has a pointer to the next place. The order of the list does not depend on the order in the array.
headis the first place. A null pointer (here -1) means "no next place".- To visit every place: start at
head, and repeat until the pointer is -1: visit the place, then follow its pointer.
| Index | names | next_stop |
|---|---|---|
| 0 | Bank | 4 |
| 1 | Park | 3 |
| 2 | Shop | 0 |
| 3 | Home | -1 |
| 4 | School | 1 |
- head = 2: Shop → Bank → School → Park → Home.
Insert without moving
- Put the new place at the end of the arrays.
- Give it the pointer of the place before it, then make that place point to the new one.
- Arduino lesson 76 has the same idea in C++.
In the exam
- 9618/21/M/J/24 Q3(b): a linked list of user IDs is built from two variables and two 1D arrays. Mark scheme: the variables are integers used as pointers, to the first element of each list; the first array is of type string and stores the data; the second array is of type integer and stores the pointers to the next item. Your
namesandnext_stoplists are those two arrays. - Q3(a): the list just after initialisation. Mark scheme: the start pointer is null, and all nodes are on the free list.
Difficulté 4/5 · 280 pièces + un petit bonus lors de la première réussite aujourd'hui
The robot's route is a linked list. names[i] et squares[i] describe a place, and next_stop[i] is the index of the next place; -1 means "the end". head is the first place. The starter visits the places in array order. Follow the pointers instead, from head until -1, so the robot passes the numbered circles in order and ends at Home.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 4/5 · 280 pièces + un petit bonus lors de la première réussite aujourd'hui
Add a new place, Library at square [7, 2], between Bank and School. Do not move anything in the lists: append the new place at the end (index 5), give it Bank's pointer, and then make Bank (index 0) point to index 5.
Cliquez sur Exécuter pour voir le résultat ici.