Lesson contents

Singly linked lists

Each node stores a value and a link to the next node. Starting at the head, follow the links to read the list.

Simple example

Link the node holding 4 to 7, and 7 to 9. Print each value and stop when the last node has no next link.

Start4→7→9
Result4 7 9
main.rs
fn main() {
    let values: [i64; 3] = [4, 7, 9];
    let following: [i64; 3] = [1, 2, -1];
    let mut node: i64 = 0;
    while node != -1 {
        println!("{}", values[(node) as usize]);
        node = following[(node) as usize];
    }
}
Output
4
7
9
Advertisements

Everyday examples

Insert a stop on a bus route

The route goes from stop 4 straight to stop 9. Add stop 7 between them.

Start4→9
Result4→7→9

Point 7 at 9 first, then change the next stop after 4 to 7. The rest of the route stays reachable.

Follow a reading trail

Cards 11, 25 and 18 each name the next book to read. Which book comes after 25?

Start11→25→18
Result18

Follow the link on card 25. A larger or smaller book number tells you nothing about the order.

Remove a playlist entry

Tracks 2, 6 and 8 play in that order. Track 6 is unavailable. What should track 2 point to?

Start2→6→8
Result2→8

Copy track 6’s next link into track 2. Playing from 2 now skips straight to 8.

Cost and limits

Following a chain of n nodes takes linear time. Inserting directly after a known node takes constant time once the new node is available.