Picture nodes and next pointers in memory, know what each operation costs, and build a linked list yourself.
A chat app shows each conversation as a thread of messages. Your team lead lists what the thread must do.
New messages join at the end, many times a second. A pinned announcement can jump to the very front. Moderators remove messages from anywhere in the thread.
Suppose the thread is an array. Pinning a message to the front moves every other message one place to the right. In a thread of 50,000 messages, that is 50,000 moves for one pin. A linked list does the same pin in three small steps, whatever the length.
Think of a train. Each carriage is coupled to the one behind it, and the engine at the front leads the way. To add a carriage at the front, you couple it to the engine's carriage and call it the new front. Nobody has to move the other carriages.
But you cannot jump to carriage 40. You walk from the front, through each coupling, until you get there. In a linked list, the carriages are nodes, the couplings are next pointers, and the front is the head.
A linked list is like a train: carriages are nodes, couplings are next pointers, and the front carriage is the head.
An array is one block of memory. Its values sit side by side, so the computer finds index 2 with arithmetic: the start address plus 2 times the size of one value.
A linked list is different. Each value lives in its own node, wherever memory had room when the node was made.
Next to its value, each node stores the address of the next node. That stored address is the next pointer. The last node stores null, which means "no next node".
The list itself remembers one address: the head, the first node. Step through the picture below and watch where each value lives.
Step by step: An array and a linked list in memory. The animated player loads in your browser.
So a linked list is a chain of nodes, each pointing at the next. Two words appear in every operation:
Predict what happens
Q A list holds 12 → 7 → 30 → 4. You start a cursor at the head. How many pointer hops does it take to reach 4?
Answer: C
Position 3 takes 3 hops: you follow next three times. The tail pointer would reach 4 in one step, but only because the list keeps that extra pointer. For any other position you walk.
Every operation does two kinds of work. First it finds the place, by walking. Then it changes a few pointers there.
Changing pointers is always a few steps. Walking is what costs.
Make a new node. Point its next at the current head. Then move head to the new node. Three steps, and no walking at all.
Insert at the head: the new node points at the old head, then head moves to it. No walking, whatever the length.
Step by step: Insert 12 at the head. The animated player loads in your browser.
To insert after a node, you first walk to it. Then the order of the two pointer changes matters. Point the new node at the next node first, and only then point the current node at the new one. Done the other way round, the rest of the list is lost.
Step by step: Insert 25 after position 1. The animated player loads in your browser.
Predict what happens
Q You insert 25 after the node holding 7, in 12 → 7 → 30 → 4. You set 7.next to the new node first, and only then try to set the new node's next. What goes wrong?
Answer: B
7.next was the only pointer to 30. Once it points at 25, no node and no variable can reach 30 or 4. Point the new node at 30 first, then re-point 7.
Exercise · Find the bug: The nodes that disappear. This function inserts a value after position k of a list, counting from 0, and k is inside the list. On a longer list, nodes go missing. Which line is wrong?
def insert_after(head, k, value):
curr = head
for _ in range(k):
curr = curr.next
node = ListNode(value)
curr.next = node
return headTo delete a value, walk with two cursors: prev and curr, one node apart. When curr holds the value, point prev.next past it. Now nothing points at the deleted node. Python, Java and JavaScript free it for you; in C++ you call delete on it yourself.
Step by step: Delete 30. The animated player loads in your browser.
Exercise · Predict the output: What is left, and how far did the walk go?. A list reads 4 → 7 → 2 → 9 → 6. The code walks with prev and curr to delete 9, counting each time it moves on. After the delete it prints the list, then the number of moves. What does it print?
class Node:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
head = None
for v in [6, 9, 2, 7, 4]:
head = Node(v, head)
target = 9
moves = 0
prev, curr = head, head.next
while curr and curr.val != target:
prev, curr = curr, curr.next
moves += 1
if curr:
prev.next = curr.next
node = head
while node:
print(node.val, end=" ")
node = node.next
print("|", moves)To reverse a list, you turn every arrow around, one node at a time. Three cursors do it: prev, curr and next. At each node, save curr.next in next, point curr.next back at prev, then move both cursors forward. Predict each arrow before the player shows it.
Reverse: save next, turn curr's arrow back at prev, move both cursors on. One walk turns every arrow.
Step by step: Reverse a four-node list. The animated player loads in your browser.
Two cursors start at the head. slow moves one node at a time; fast moves two. When fast runs off the end, slow is at the middle. This finds the middle in one walk, without counting the nodes first.
Find the middle: fast moves two nodes for every one that slow moves, so slow stops halfway.
Step by step: Find the middle with slow and fast. The animated player loads in your browser.
Predict what happens
Q A list has 6 nodes: 3 → 8 → 5 → 9 → 2 → 6. slow and fast start at 3. Where is slow when fast can no longer move two nodes?
Answer: B
Round 1: slow 8, fast 5. Round 2: slow 5, fast 2. Round 3: slow 9, and fast moves past the end. With an even count, this loop stops at the second middle.
Here is every operation side by side. The "given the node" rows matter: once you hold a pointer to the right node, a linked list changes it in O(1). An array still has to shift.
| Operation | Singly linked list | Doubly linked list | Array |
|---|---|---|---|
| Access by index i | O(n): i hops from the head | O(n): walk from the nearer end | O(1): one jump |
| Search for a value | O(n) | O(n) | O(n), or O(log n) when sorted |
| Insert at the head | O(1) | O(1) | O(n): every value shifts right |
| Delete at the head | O(1) | O(1) | O(n): every value shifts left |
| Insert at the tail | O(1) with a tail pointer, O(n) without | O(1) | O(1) on average, when there is spare room |
| Delete at the tail | O(n): you need the node before the tail | O(1): the tail knows its prev | O(1) |
| Insert or delete in the middle, given the node | O(1) (delete needs the node before it) | O(1) | O(n): values shift |
| Insert or delete in the middle, given an index | O(n): walk there first | O(n) | O(n) |
| Extra memory for each value | one pointer | two pointers | none (some spare room) |
A doubly linked list adds a second pointer to each node, prev, which points back. It costs more memory, and every change updates two pointers instead of one. In return, a node can be unlinked without walking to the node before it, and the list can be walked in both directions.
Exercise · Put it in order: Add a node at the back. Arrange the lines into a function that adds a value at the back of a list, with no tail pointer, and returns the head.
def append_node(head, value):
node = ListNode(value)
if head is None:
return node
curr = head
while curr.next:
curr = curr.next
curr.next = node
return head
while curr:Predict what happens
Q A singly linked list keeps a tail pointer. Why is deleting the tail still O(n)?
Answer: C
The tail pointer reaches the last node in one step, but deleting it means re-pointing the node before it. Without prev pointers, that node is found only by walking. A doubly linked list removes the walk.
Now drive the list yourself. Type a value, pick an operation and watch it run step by step. The counter shows the pointer hops, and the panel below it shows what the same operation would cost on an array.
Try these five, in order:
curr walk the whole list first.The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the structure yourself. The lab gives you a Node class with a value and a next pointer, and a LinkedList class that keeps head, tail and a count. You write six methods: push_front, push_back, pop_front, find, reverse and size. The seventh, to_list, is already written, so the tests can look inside your list.
Each test creates a new, empty list, calls your methods in order and compares every value they return. When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Three rules keep the list correct after every method:
head is the first node, or null when the list is empty.tail is the last node, or null when the list is empty. So when the list goes from empty to one node, or from one node to empty, both change.count goes up by one on each insert and down by one on each pop.Exercise · Break it: Find the input that loses a value. This queue keeps a head and a tail. A positive number adds that value at the back, and 0 takes one from the front (-1 when the queue is empty). At the end it takes out everything that is left. Find a list of operations where it gives the wrong answer.
class Node:
def __init__(self, val):
self.val = val
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def push_back(self, val):
node = Node(val)
if self.tail is None:
self.head = node
else:
self.tail.next = node
self.tail = node
def pop_front(self):
node = self.head
self.head = node.next
return node.val
def run(ops):
q = Queue()
out = []
for op in ops:
if op > 0:
q.push_back(op)
elif q.head is None:
out.append(-1)
else:
out.append(q.pop_front())
while q.head is not None:
out.append(q.pop_front())
return outBuild it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a linked list when most of the work is inserting and deleting at the front or the back. It also fits changes at a node you already hold a pointer to. Job queues add at the back and take from the front. An undo history adds and removes at one end.
The best-known use is the least-recently-used cache. A hash map finds a key's node in one step, and a doubly linked list moves that node to the front in one step. Neither structure could do both on its own.
Choose an array when you read by index, binary search a sorted list, or loop over the values many times. Each linked-list hop may land anywhere in memory, so walking a list is several times slower than scanning an array of the same length.
Each node also carries at least one pointer next to its value. For 8-byte values, a singly linked list can use twice the memory of an array. For a few hundred values, an array is almost always the faster choice.
Walking with the head itself, as in while head is not None: head = head.next, leaves head at null when the loop ends. The list is still in memory, but nothing points at its first node any more. Walk with a separate cursor: curr = head.
while curr.next.value != target crashes when curr is the last node, because curr.next is null and null has no value. The empty list crashes even earlier. Check curr is not None before every hop, and decide what an empty list should return.
In reverse, writing curr.next = prev before nxt = curr.next loses the rest of the list after the first step. On 1 → 2 → 3, the loop stops after node 1, and the list becomes 1 alone. Save first, then turn the arrow.
The classic mistake: turn curr's arrow before saving next, and the rest of the list is lost.
To delete a node you need the node before it, because that is the pointer you change. A loop that stops on the node to delete, as in while curr.value != target, has gone one hop too far in a singly linked list. Stop when curr.next.value == target, or walk with prev and curr together.
If a bug points the tail back at an earlier node, as in tail.next = head, the list has a cycle. Every walk that waits for null now loops for ever, and the tests time out. If a lab test runs out of time, check where your tail's next points.
Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The picture
Q1/2 What does a node in a singly linked list store?
Answer: B
A node holds its value and one pointer, next. The list itself remembers only the head, so the order lives in the chain of next pointers.
Q2/2 Why can an array reach index 1,000 in one step, while a linked list cannot?
Answer: A
An array is one block: start address plus 1,000 times the value size. A list's nodes are scattered, and each address is known only from the node before it.
Checkpoint · Costs
Q1/3 How many pointer hops does inserting at the head of a 1,000,000-node list take?
Answer: A
Insert at the head changes two pointers and never walks. The length of the list does not matter.
Q2/3 A singly linked list keeps a tail pointer. Which operation at the back is still O(n)?
Answer: C
Deleting the tail means re-pointing the node before it, and in a singly linked list only a walk from the head finds that node. Inserting needs only the tail itself.
Q3/3 You hold a pointer to a node in the middle of a doubly linked list. What does unlinking it cost?
Answer: A
A doubly linked node knows both neighbours, so two pointer changes remove it. Nothing shifts, and nothing walks.
Checkpoint · Pointer moves
Q1/3 You insert a new node after node A, whose next is B. Which order of steps is safe?
Answer: A
Once A's next points at the new node, A no longer leads to B. Set the new node's next first, while B is still reachable.
Q2/3 In reverse, the loop body saves nxt = curr.next, sets curr.next = prev, then moves prev and curr. What happens if you drop the first line and move curr to curr.next instead?
Answer: B
After the turn, curr.next is the old prev. Only the saved nxt still reaches the unvisited part of the list.
Q3/3 slow moves one node and fast moves two, both from the head of 4 → 1 → 6 → 2 → 9. Where is slow when the loop stops?
Answer: B
Round 1: slow 1, fast 6. Round 2: slow 6, fast 9, the last node, so fast cannot move two more. slow has gone half as far as fast: the middle.
Checkpoint · Mistakes and choices
Q1/2 This loop looks for target: while curr.next.value != target: curr = curr.next. When does it crash?
Answer: B
On the last node, curr.next is null. Reading null's value is an error in every language. Check for null before each hop.
Q2/2 Which job suits an array better than a linked list?
Answer: C
Binary search jumps to the middle again and again. An array does each jump in one step; a linked list would walk half the list each time.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.