4 / 7 · Intermediate
Linked lists
Adding a value at the front of a linked list changes two pointers, whether the list holds 4 values or 4 million.
Jump to the 10 practice questionsYou will learn
- Build a list from nodes and next pointers
- Count visits and pointer changes
- Choose between an array and a linked list
Before this: Queues
1Explain
Nodes and pointers
An array keeps its values side by side, which is why the front is expensive to change. A linked list drops that rule. Each value lives in its own small record called a node, and the nodes can sit anywhere in memory. MIT's 6.006 notes describe a node with two fields: the item, and next, a pointer to the following node. The list itself only remembers the first node, called the head. The last node's next is null, which marks the end.
// one node per value: { value, next }
let head = null;
for (const v of [4, 30, 7, 12]) head = { value: v, next: head };
// walk the list
for (let n = head; n !== null; n = n.next) console.log(n.value); // 12, 7, 30, 412
7
30
42Problem
The two fields
What two fields does a node of a singly linked list hold?
Hint
One holds the value, one points onward.
Solution
Answer: item and next
MIT's notes: node.item and node.next, a pointer to the following node.
3Explore
Walking the list
To read the list you start at head and follow next pointers one by one, like following a chain of notes that each say where the next note is hidden. That has a cost. There is no formula for the address of the fourth node, so getting the value at position i means visiting i + 1 nodes. MIT lists get at(i) for a linked list as O(n), where the array managed it in one step.
find starts at head and follows next. The cost is the number of nodes visited.
Press a button: each one runs one operation and shows what it cost.
[12,7,30,4]Total steps 0
4Problem
Searching for 30
Same list: how many nodes does a search for 30 visit?
Hint
12, 7, then 30.
Solution
Answer: 3
12, 7, then 30: found on the third visit.
5Problem
Searching for 99
Same list: how many nodes does a search for 99 visit before it reaches null?
Hint
A missing value means every node.
Solution
Answer: 4
A missing value means visiting every node: all 4.
6Explore
Changing the front
The payoff comes when you change the list. To put a new value at the front, make a node whose next is the current head, then point head at the new node. Two pointer changes, and nothing else moves. Deleting the front node is one change: point head at head.next. Compare that with the array, where the same operations moved every value.
A new front node costs 2 pointer changes; removing the front costs 1. Nothing else moves, however long the list.
Press a button: each one runs one operation and shows what it cost.
[12,7,30,4]Total steps 0
7Problem
Insert at the front
List 12 → 7 → 30 → 4. How many steps does inserting a new value at the front take (pointer changes)?
Hint
new.next = head, then head = new.
Solution
Answer: 2
new.next = head, then head = new. No node is visited and nothing moves.
8Problem
The array, for comparison
An array holds 1,000 values with room to spare. How many steps does inserting at the front take?
Hint
1,000 moves and 1 write.
Solution
Answer: 1001
1,000 moves + 1 write = 1,001, against 2 pointer changes for a linked list.
9Explain
Inserting in the middle
In the middle, the work is finding the spot. To insert at position i you walk to the node just before it (i visits), then do the same two pointer changes: new.next = prev.next, then prev.next = new. The order matters. If you set prev.next first, the rest of the list is lost, because nothing points to it any more. In the lab a step is one node visited or one pointer changed, so inserting at position 2 of a 4-node list costs 2 visits plus 2 changes, 4 steps.
First the new node points at the rest of the list, then prev points at the new node. The other order would lose the rest.
let head = { value: 12, next: { value: 7, next: { value: 30, next: null } } };const prev = head.next;const node = { value: 99, next: null };node.next = prev.next;prev.next = node;console.log(head.next.next.value);
99
10Problem
The safe order
When inserting after node p, which order of steps keeps the rest of the list?
Hint
Which pointer is the only way to reach the rest?
Solution
Answer: new.next = p.next, then p.next = new
Setting p.next first would lose the only pointer to the rest of the list.
11Problem
Insert at position 2
Same list: inserting at position 2 costs how many steps (visits plus pointer changes)?
Hint
2 visits, 2 changes.
Solution
Answer: 4
Visit nodes 0 and 1 to reach the node before position 2, then 2 pointer changes: 2 + 2 = 4.
12Problem
Delete at position 3
Same list: deleting the node at position 3 (the 4) costs how many steps?
Hint
3 visits to reach the node before it, then 1 change.
Solution
Answer: 4
Visit nodes 0, 1, 2 to reach the one before it (3 visits), then change 1 pointer: 4.
13Explain
Array or linked list
A linked list is a good fit when most changes happen at a place you already hold a pointer to, such as the front, and you rarely need position i. Queues and stacks can be built from linked lists, and so can the chains inside a hash table in the next unit.
| Operation | Array (n values) | Linked list (n nodes) |
|---|---|---|
| Get the value at position i | 1 | i + 1 visits |
| Insert at the front | n moves + 1 write | 2 pointer changes |
| Delete the front | 1 read + (n − 1) moves | 1 pointer change |
| Insert at position i | (n − i) moves + 1 write | i visits + 2 changes |
| Find a value | up to n reads | up to n visits |
14Problem
A job for a linked list
Which job suits a linked list better than an array?
Hint
Which changes happen at the front?
Solution
Answer: Adding and removing at the front many times
Front changes are 1 or 2 pointer changes; position 500 would mean 501 visits each time.
15Practice
Write a list walker
Walk the list and collect its values. It should print 12 7 30 4 (each new node went in at the front).
12 7 30 4let head = null;
for (const v of [4, 30, 7, 12]) head = { value: v, next: head };
function toArray(head) {
const out = [];
// Start at head and follow next until you reach null,
// pushing each node's value into out.
return out;
}
console.log(toArray(head).join(" "));
Hint
Stop when n itself is null, not when n.next is null, or the last node is skipped.
A solution
let head = null;
for (const v of [4, 30, 7, 12]) head = { value: v, next: head };
function toArray(head) {
const out = [];
for (let n = head; n !== null; n = n.next) out.push(n.value);
return out;
}
console.log(toArray(head).join(" "));16Practice
Relink the pointers
Finish both functions by relinking pointers. It should print 12 7 99 30 4 and then 12 99 30 4.
12 7 99 30 4
12 99 30 4function list(...vals) { let h = null; for (let i = vals.length - 1; i >= 0; i--) h = { value: vals[i], next: h }; return h; }
const show = (h) => { const out = []; for (let n = h; n !== null; n = n.next) out.push(n.value); return out.join(" "); };
let head = list(12, 7, 30, 4);
function insertAfter(node, v) {
// Make a node whose next is node.next, then point node.next at it.
}
function deleteAfter(node) {
// Point node.next past the node that follows.
}
insertAfter(head.next, 99);
console.log(show(head));
deleteAfter(head);
console.log(show(head));
Hint
The new node must point at what node.next pointed at before.
A solution
function list(...vals) { let h = null; for (let i = vals.length - 1; i >= 0; i--) h = { value: vals[i], next: h }; return h; }
const show = (h) => { const out = []; for (let n = h; n !== null; n = n.next) out.push(n.value); return out.join(" "); };
let head = list(12, 7, 30, 4);
function insertAfter(node, v) {
node.next = { value: v, next: node.next };
}
function deleteAfter(node) {
node.next = node.next.next;
}
insertAfter(head.next, 99);
console.log(show(head));
deleteAfter(head);
console.log(show(head));17Explain
Common mistakes
let head = { value: 12, next: null };
let n = head;
while (true) {
console.log(n.value);
n = n.next;
}12
TypeError: Cannot read properties of null (reading 'value') (line 4)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
The loop never checks for the end, so it reads .value from null. Loop while n !== null.
18
Summary
- A linked list stores each value in a node with a next pointer; the list keeps head.
- Insert or delete at the front changes 1 or 2 pointers; nothing moves.
- Reaching position i takes i + 1 visits, so get at(i) is O(n).
- Set new.next before relinking the previous node.