Week 34 · Phase 4 — The Toolbox
Chains of data and dynamic memory — beloved of textbooks, rarely the right answer in real code.
Photo · henry perks / Unsplash
You can store a sequence of values two ways: in a row (an array — Week 29) or in a chain (a linked list, this week). They have the same logical capability — keep N values, walk through them, add and remove — but very different physical layouts and very different performance characteristics.
Linked lists are the canonical example for teaching pointers, and the canonical example of how textbooks lie about real-world performance. By the end of today you'll know what they are, when to use them, and why you almost never should.
A linked list is a sequence of nodes. Each node holds a value and a pointer to the next node. The list itself is a pointer to the first node (the "head"). The last node's "next" pointer is null.
struct Node {
int value;
Node* next;
};
Node* head = new Node{10, nullptr};
head->next = new Node{20, nullptr};
head->next->next = new Node{30, nullptr};
// to walk the list:
for (Node* n = head; n; n = n->next) {
std::cout << n->value;
}
Compare to an array: int arr[] = {10, 20, 30}. Same data, but the array packs them in 12 contiguous bytes, while the linked list scatters them across the heap, each node 16+ bytes (value + pointer + allocator overhead).
Linked lists are theoretically better at:
Linked lists are dramatically worse at almost everything else:
ints, that's a 4× memory cost.The textbook says "use a linked list if you do lots of inserts/deletes". Reality says "even then, a vector is usually faster up to several thousand elements, because cache effects swamp the algorithmic advantage". The classic advice is wrong on modern hardware.
For everything else: std::vector.
Variations exist:
std::list): each node has both next and prev. You can walk in either direction; deletion of a known node is O(1).next points back to the head. Useful for ring buffers, round-robin schedulers.Almost nowhere — and that's the point. AI workloads are vector- and matrix-heavy, and contiguous memory access is everything. You'd struggle to find a linked list in any modern AI framework's hot path. Where they appear at all is in metadata structures (the operator dependency graph, the training callback chain) where O(1) splicing is occasionally useful.
Linked lists: famous, often wrong. Reach for a vector first.
std::vector<int> of 1,000,000. Compare. The vector should be at least 5× faster.std::list from the STL — it's the standard's doubly-linked list. Compare with both.Two simple data structures with very specific access patterns — and surprisingly profound applications.
Week 35 is Stacks & Queues.
Photo free under the Unsplash license. Chain · henry perks.