Lesson contents

Choosing a data structure

Start with the question you need to answer. Finding the next person, the newest item and a person by ticket number are three different jobs.

Simple example

Three people arrive with tickets 12, 7 and 9. If arrival order matters, the first answer is 12. Print the first ticket.

Start12 7 9
Result12
main.rs
fn main() {
    let tickets: [i64; 3] = [12, 7, 9];
    println!("{}", tickets[0]);
}
Output
12
Advertisements

Everyday examples

Serve the first arrival

Tickets 41, 12 and 86 arrive in that order. Who gets the next turn?

Start41 12 86
Result41

Use a queue. Ticket numbers identify people. Their arrival order decides who goes first.

Undo the last change

Edits 41, 12 and 86 were saved in that order. Which edit does Undo remove?

Start41 12 86
Result86

Use a stack. Remove edit 86 first so the earlier edits stay in place.

Find the pickup shelf

A parcel card lists ticket 41 on shelf 2 and ticket 86 on shelf 5. Which shelf holds ticket 86?

Start41→2 86→5
Result5

Use a map from ticket to shelf. You can look up 86 even if its owner arrived last.

Cost and limits

A small list is easy to scan. A direct lookup can save work when you already know the key. Count the work for the operation that matters most.