An array stores its elements in one contiguous block, so you can jump to index
i instantly. A linked list stores each element in its own box — a node
— and each node points to the next one. The nodes can live anywhere in memory;
the chain of pointers is what keeps them in order, like a scavenger hunt where
each clue tells you where to find the next one.
In Go a singly linked list node looks like:
ListNode:
value
next // reference to the next node, or nothing if this is the last one
Val is the data; Next points to the following node, or is nil at the end of
the list. You hold a list by holding its head (the first node). The list
1 → 2 → 3 is a head node with Val: 1 whose Next is a node with Val: 2, and
so on, ending in Next: nil.
The trade-off: no random access. To reach the 5th element you have to follow
Next five times — O(n) — whereas an array jumps there in O(1). Linked lists
also spend extra memory on all those pointers.
Almost every linked-list algorithm is built from:
Next until you hit nil.Next to splice nodes in or out.The next lesson drills both. Throughout this section, lists are written as
space-separated values, e.g. 1 2 3 for 1 → 2 → 3, and an empty line is the
empty list.