Linked lists: nodes, pointers and the head
1 A chain of clues
The arrays lesson showed that inserting at the front of an array moves every value one place right. With 10⁵ values and 10⁵ inserts at the front, that is around 10¹⁰ steps, and the code gets TLE. The values had to move because an array keeps them side by side.
A linked list drops that rule. Its values can sit anywhere in memory, and each one says where the next one is.
A treasure hunt works the same way. Cards are hidden around a house. Each card has a number on it and says where the next card is. We are told only where the first card is, and the last card says "end". To read the fourth number, we have to visit the first three cards.
In memory, each card is a node. A node holds a value, val, and the address of the next node, next. Here are four nodes, in the order they sit in memory:
Starting at 120 and following the addresses gives 7, 2, 9, 4. We draw that order as circles and arrows, and leave the addresses out:
The first node is the head. The program knows the list only through a variable that holds the head's address, 120. The last node is the tail. Its next is null, an address that means "no node". An empty list has a null head.
2 The node in code
On oneby7 and on LeetCode, every linked list problem uses the same class, ListNode. The function gets the head node, never an array. The examples write a list as [7, 2, 9, 4], but that is only how they print it.
To try code on our own, we build the list by hand. We build it from the back, so each node's next node already exists:
C++
A real address. next is a pointer, so it holds the next node's address, and nullptr marks the end. A node made with new stays in memory until we delete it.
A reference. next refers to the next node, and null marks the end. A new node's next is null until we set it.
A reference. next refers to the next node, and None marks the end.
A reference. next refers to the next node, and null marks the end.
A pointer. Next holds the next node's address, and nil marks the end. &ListNode{…} makes a node and gives its address.
Each node owns the next. next is Some(node) for a next node and None at the end. A node owns the rest of the list, so we build from the back, and the head is an Option<Box<ListNode>> too.
A reference. next refers to the next node, and null marks the end.
3 Walking the list
To read every value, we follow the cards. A pointer cur starts at the head. At each node, we use cur.val, then move on with cur = cur.next. Once cur is null, we have passed the tail, and the loop stops. Here the walk counts the nodes:
We move cur and leave head where it is. If the loop moved head itself, head would be null at the end, and no variable would know where 7 is. That is losing the head. In the treasure hunt, it is throwing away the note that says where the first card is. The nodes are still in memory, but nothing leads to them.
C++
-> follows the pointer. cur->next reads the next of the node that cur points at.
Copying a reference is cheap. cur = head copies the head's reference, not the list.
Copying a reference is cheap. cur = head copies the head's reference, not the list.
Copying a reference is cheap. cur = head copies the head's reference, not the list.
Copying a pointer is cheap. cur := head copies the head's address, not the list.
cur borrows. &head lets cur look at the list without taking it. while let Some(node) = cur stops at the None after the tail.
Copying a reference is cheap. cur = head copies the head's reference, not the list.
Our list gives 4. Searching for a value is the same walk with one if: return true when cur.val matches, and false once the loop ends. A walk visits each node once, so it takes O(n) time and O(1) extra space.
4 Inserting: two links, in the right order
To add 5 before the head, the new card only needs the old first card's address. Then the head moves to the new card:
newNode.next = head
head = newNode
That is two steps, however long the list is, so it is O(1). The function returns the new head, because the caller's variable still points at 7.
Inserting 6 after the node 2 changes two addresses. The new node must point at 9, and 2 must point at the new node. We call the node we insert after prev. In memory, the new node lands at 280:
The same two lines in the other order lose the rest of the list:
Step 2 wrote over the only copy of 9's address. So step 3 copied 6's own address, and a walk now goes round 6 forever. The nodes 9 and 4 are lost. In the treasure hunt, we rewrote card 2 before copying down where it pointed.
The rule is to link the new node to the rest first, and only then link it in. Inserting after the tail works with the same two lines. There, prev.next is null, so the new node's next is null too.
5 Deleting: skip the node
To delete 9, the node before it must skip it. Node 2 should point at 4 instead, and one line does that:
prev.next = prev.next.next
We need the node before the one we delete. A node holds only the address of the node after it, so standing on 9 we cannot get back to 2. That is why a walk for a delete stops one node early.
The head has no node before it. To delete the head, the head moves on instead: head = head.next. The old first node is lost on purpose.
Here are the three changes in code. Each is a fixed number of steps, so each is O(1):
C++
Free what you remove. The skipped node stays in memory until delete. So deleteAfter keeps its address in removed, links past it, and then deletes it.
Nothing to free. Once no reference leads to the skipped node, the garbage collector frees it.
Nothing to free. Once no reference leads to the skipped node, Python frees it.
Nothing to free. Once no reference leads to the skipped node, the garbage collector frees it.
Nothing to free. Once no pointer leads to the skipped node, the garbage collector frees it.
take() keeps the order right. prev.next.take() lifts the rest of the list out of prev and leaves None. The new node then owns the rest, so it cannot be lost. In delete_after, the removed node is freed when removed goes out of scope.
Nothing to free. Once no reference leads to the skipped node, the garbage collector frees it.
On our list, insertAtHead with 5 gives 5, 7, 2, 9, 4. insertAfter on 2 with 6 gives 7, 2, 6, 9, 4. deleteAfter on 2 gives 7, 2, 4.
6 Reaching position k
Problems number the nodes from 1, so the head is node 1. To insert or delete at node k, we stand on node k − 1 and use the lines above. The walk starts on node 1, and each move goes one node further. Here we delete node 4:
Two moves reached node 3. The table shows the pattern:
| Position k | Stand on node | Moves from the head |
|---|---|---|
| 2 | 1 | 0 |
| 3 | 2 | 1 |
| 4 | 3 | 2 |
| k | k − 1 | k − 2 |
So the walk is a loop of k − 2 moves, then one deleteAfter or insertAfter. The walk costs O(k), and the change itself is O(1).
Node 4 was the tail, and it needed no extra code. Its next was null, so node 3's next became null. Inserting at k = n + 1, after the tail, works the same way.
Position 1 is different. It has no node before it, so it needs its own branch: head = head.next to delete, or insertAtHead to insert. The dummy node lesson puts a spare node before the head, so that k = 1 works like any other k.
7 Linked list or array
The two give opposite costs. The array finds any index at once but must shift values. The list never shifts, but must walk to find anything.
| Operation | Array | Linked list |
|---|---|---|
| Read the i-th value | O(1) | O(n), a walk |
| Insert or delete at the front | O(n), a shift | O(1) |
| Insert or delete next to a node we hold | O(n), a shift | O(1) |
| Insert or delete at position k | O(n) | O(k) walk + O(1) |
| Insert at the end | O(1) on average | O(n) walk, O(1) if we keep the tail |
| Search for a value | O(n) | O(n) |
The list also costs memory: every node carries a next address beside its value. And a walk is slower than a loop over an array of the same length, though both are O(n). The array's values sit together, and the computer reads neighbours in one go. The list's nodes are scattered, so each step jumps somewhere new.
8 Mistakes, and when to use it
- Reading through null.
cur.valorcur.nexton a nullcuris a Runtime Error. A search written as "move whilecur.valis not the target" runs off the end when the target is missing: [7, 2, 9, 4] with target 5. Checkcuris not null before reading from it. - Moving
headinstead ofcur. After counting withhead, the head is null, and printing the list prints nothing. - Linking in the wrong order. Inserting 6 after 2 with
prev.next = newNodefirst loses 9 and 4, as the steps showed. - Walking k − 1 moves. Then
prevstands on node k itself. Deleting node 3 of [7, 2, 9, 4] gives [7, 2, 9] instead of [7, 2, 4]. - Forgetting position 1. Without its own branch, the walk for k = 1 leaves
prevon node 1, and the code removes node 2. [7, 2, 9, 4] gives [7, 9, 4] instead of [2, 9, 4]. - Forgetting to return the new head. After a change at the front, the caller still holds the old first node.
- The empty list. A null head has no
next, sohead.nextis a Runtime Error. Inserting at k = 1 into an empty list returns the new node as the head.
The problems in this subtopic hand us a head and ask us to walk, insert into or delete from the list by hand. Each one is a walk to the right node, usually the one before the change, and then one or two next changes. The next lessons build on this. A doubly linked list keeps a link back as well, fast and slow pointers walk at two speeds, and the dummy node removes the head's special case.
Before changing a next, ask what it points at now. If nothing else leads there, save that address first.
Practice it
- Traverse a linked listEasy
- Length of a linked listEasy
- Search in a linked listEasy
- Insert at the headMedium
- Insert at the tailMedium
- Insert at position KMedium
- Insert before the value XMedium
- Delete the headMedium
- Delete the tailMedium
- Delete the K-th nodeMedium
- Delete the node with value XMedium
- Delete Node in a Linked ListMedium
- Remove Linked List ElementsEasy
- Design Linked ListMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.