NCL 407: Linked Lists
In the previous lesson, we gave an array a header containing its length.
That let the array keep track of how many elements it contained as we appended, inserted, and removed them.
But inserting into the middle of an array required moving every element that followed.
For a stride-3 array, inserting one record could mean copying a lot of values just to open a gap.
What if the records didn't need to be next to each other?
Linking Records
Let's keep the idea of a header.
This time, it contains two values:
| Address | Meaning |
|---|---|
$100 |
Length |
$101 |
First record |
Suppose our records have a stride of 3:
| Offset | Field |
|---|---|
0 |
Next |
1 |
Name |
2 |
Score |
The first field of every record contains the address of the next record.
Our records don't even need to be near the header:
| Address | Field | Value |
|---|---|---|
$200 |
Next | 0x300 |
$201 |
Name | "NEMI" |
$202 |
Score | 9000 |
$300 |
Next | 0x180 |
$301 |
Name | "ALICE" |
$302 |
Score | 7200 |
$180 |
Next | -1 |
$181 |
Name | "BOB" |
$182 |
Score | 5100 |
The header contains:
$100 = 3
$101 = 0x200
So the first record is at $200.
That record points to $300.
$300 points to $180.
And $180 contains -1 for its next address, meaning there isn't another record.
Logically:
$200 → $300 → $180 → end
This is a linked list.
Why -1?
Every value from 0x000 through 0xFFF is a valid memory address, including 0.
-1 is outside that range, so we can use it to mean no address.
Physical and Logical Order
Our records physically appear at:
$180
$200
$300
But the list says their order is:
$200
$300
$180
The order of a linked list is determined by its links, not by where its records are stored.
With an array, we could calculate the address of any record:
address = base + index × stride
A linked list gives up that relationship.
Instead, we start with the first record and follow its links.
Walking the List
Suppose we want record 0.
The header tells us where it is:
#first $101
#record $000
MOVE #record #first
Now:
#record = 0x200
Because the first field of the record is its next pointer, we can follow it with indirect memory:
MOVE #record [#record]
Now:
#record = 0x300
Do it again:
MOVE #record [#record]
and:
#record = 0x180
One more gives:
#record = -1
We've reached the end.
This is called traversing, or walking, the list.
A complete walk can repeat until the next address is -1:
#first $101
#record $000
MOVE #record #first
:walk
BEQ :done #record -1
-- Use the current record here.
MOVE #record [#record]
JUMP :walk
:done
This reveals the main cost of a linked list.
With an array:
record = base + index × stride
If we want record 500, we can calculate its address immediately.
With a linked list, reaching record 500 means following 500 links.
Do we need to store the length?
Not necessarily.
We could find the length by starting at the first record and following links until we reach -1, counting each record along the way.
But that means finding the length requires walking the entire list.
By keeping the length in the header and updating it whenever we insert or delete a record, the program can read it immediately.
We're trading one extra piece of metadata for less work later.
Inserting a Record
Let's treat our records as a small high-score table:
NEMI 9000
ALICE 7200
BOB 5100
Now Charlie scores 6000.
He belongs between Alice and Bob:
NEMI → ALICE → CHARLIE → BOB
With the array from the previous lesson, we'd need to move records to open a gap.
With a linked list, we can put Charlie wherever we have three free locations.
Suppose that's $280:
| Address | Field | Value |
|---|---|---|
$280 |
Next | 0x180 |
$281 |
Name | "CHARLIE" |
$282 |
Score | 6000 |
Charlie now points to Bob.
Then we change Alice's next pointer from:
0x180
to:
0x280
The list becomes:
$200 → $300 → $280 → $180 → end
Finally:
INC $100
The length is now 4.
Nothing else moved.
We created the new record, connected it to Bob, changed Alice's link, and updated the length.
Reordering Records
Because the links determine the order, records can also be rearranged without moving their contents.
Suppose:
A → B → C → D
and we want to swap B and C.
We can change the links to produce:
A → C → B → D
Conceptually:
A.next = C
C.next = B
B.next = D
The records themselves stay exactly where they were.
Don't lose the rest of the list
When changing several links, preserve any address you'll still need before overwriting it.
If you overwrite the only pointer leading to part of the list, those records are no longer reachable from the header.
This makes linked lists particularly useful for small collections whose order changes frequently.
A high-score table is a good example.
It might contain only ten records. Walking several links is cheap, while new scores may frequently need to be inserted somewhere in the middle.
If we limit the table to ten scores, we could:
find insertion point
↓
insert new record
↓
increment length
↓
length > 10?
↓
remove final record
For that kind of work, cheap insertion and reordering may matter much more than being able to jump directly to an arbitrary index.
Deleting a Record
Suppose our list is:
NEMI → ALICE → CHARLIE → BOB
and we remove Charlie.
Alice points to Charlie, and Charlie points to Bob.
Instead, make Alice point directly to Bob:
NEMI → ALICE → BOB
Charlie is no longer part of the list.
We can free Charlie's three memory locations and decrement the length.
Again, none of the remaining records need to move.
Choosing the Trade-Off
Arrays and linked lists make different operations cheap.
| Need | Array | Linked list |
|---|---|---|
| Find a record by index | Calculate its address | Follow links |
| Walk records in order | Easy | Easy |
| Insert in the middle | Move later records | Change links |
| Delete from the middle | Move later records | Change links |
| Reorder records | Move records | Change links |
| Keep records together | Naturally | Not required |
Neither representation is simply better.
An array is a good fit when direct indexed access matters.
A linked list can be a good fit when the collection is small and records are frequently inserted, removed, or reordered.
The useful data structure is the one whose cheap operations match the work your program does most often.
Fragmentation
Scattered records come with another consequence.
After repeatedly adding and removing records, we might end up with used memory separated by gaps:
| Region | State |
|---|---|
$180–$182 |
Record |
$183–$1FF |
Free |
$200–$202 |
Record |
$203–$37F |
Free |
$380–$382 |
Record |
There may still be plenty of free memory, but it isn't all together.
This is called fragmentation.
Linked structures can make good use of scattered free space, but repeated allocation and deletion can make memory increasingly fragmented.
Defragmentation
Fragmented memory can sometimes be reorganized by moving the remaining data into a more compact arrangement.
This is called defragmentation.
Moving linked records also means updating the pointers that refer to them.
Correctly finding and updating all of those references is a much larger memory-management problem.
We aren't going to build a defragmenter here.
It's Still Just Memory
There's nothing special in NCL called an array.
There's nothing special called a linked list either.
For an array, we agreed that elements occupied consecutive locations according to a predictable stride.
For this linked list, we've agreed that:
the header stores the length and first record
each record begins with the address of the next record
-1 means there is no next record
The processor only sees memory locations, values, and addresses.
We provide the structure.
Do real computers use linked lists?
Yes.
Linked structures are a common low-level technique. Records can contain addresses that connect them to other records without requiring those records to be physically adjacent in memory.
This is useful when elements need to be inserted, removed, or rearranged without moving all of the surrounding data.
The trade-off is the same: following links takes work, and each record needs space for its pointer, but changing the structure can require very little data movement.
Combining Structures
We'll return to arrays for the next few lessons because their predictable layout makes the ideas we're about to explore easier to see.
That doesn't mean these techniques have to remain separate.
An array can contain pointers to records.
A linked record can point to an array.
A record can point to another linked list.
Once addresses themselves are data, these structures can be combined however the problem requires.
They're not special NCL data types.
They're agreements about what some memory means.
Try It
A linked list has this header:
$100 = 3
$101 = 0x200
Its stride-3 records begin at:
$200
$300
$400
and are currently linked:
$200 → $300 → $400 → end
A new stride-3 record has already been written at $280.
Insert $280 between $300 and $400.
Update the list length.
Do not move any record.
Show me one solution
The new record needs to point to $400:
MOVE $280 0x400
Then $300 needs to point to the new record:
MOVE $300 0x280
Finally, update the length:
INC $100
The resulting list is:
$200 → $300 → $280 → $400 → end
We've seen how records can form a collection by pointing to one another, trading direct indexed access for cheap insertion, deletion, and reordering.
In the next lesson, NCL 408: Searching Arrays, we'll return to strided arrays and find a record when we know what it contains, but not its index.