Mental model
An array keeps its elements side by side, so it can compute where element i lives. A linked
list gives that up. Every element sits in its own small object, a node, which holds the value
and a reference to the next node. The nodes can be anywhere in memory; the only thing that holds
them together is the chain of next references.
The list object itself stores very little:
head: the first node, or null when the list is empty.tail: the last node, or null when the list is empty. Optional, but it changes what append costs.count: the number of nodes, so asking for the size does not need a walk.
The last node's next is null, which is how a walk knows it has reached the end. In the lab, each
box is a node and each arrow is a next pointer. Watch the Reverse in place preset: the boxes
do not move, only the arrows do. That is the whole idea of a linked structure. Changing the shape
means rewriting a few references, not copying elements.
The operations, pointer by pointer
Prepend
node = new Node(value)
node.next = head
head = node
if tail is null: tail = node # the list was empty
count += 1
Two or three pointer writes, no matter how long the list is: O(1). The order matters. If you
set head = node first, the old head is no longer reachable and you cannot link to it.
Append
node = new Node(value)
if tail is null: head = tail = node
else:
tail.next = node
tail = node
count += 1
Also O(1), but only because the list keeps tail. Without it, append has to walk from the head
to find the last node, which is O(n). Many hand-written lists in interview answers forget this.
Find
There is no index arithmetic. To reach position i you follow next exactly i times, so a search
by value or a lookup by index is O(n) in the worst case. The teaching index_of returns the
position of the first match, or -1 when the walk falls off the end.
Remove by value
To unlink a node you must change the next of the node before it. A singly linked list has no
backward pointer, so the walk carries two references: previous and current.
previous = null, current = head
while current is not null and current.value != value:
previous, current = current, current.next
if current is null: return false # not found
if previous is null: head = current.next # removing the head
else: previous.next = current.next
if tail == current: tail = previous # removing the tail
count -= 1
return true
Three cases need care, and the lab's Remove from the middle preset shows all of them: the match is
the head (previous is null), the match is the tail (tail must move back), and the value is not
present. Forgetting the tail case leaves tail pointing at a detached node, and the next append
silently disappears into it.
Once unlinked, nothing refers to the node. C#, Java and Python reclaim it with the garbage collector.
The C++ version owns each node through a std::unique_ptr, so overwriting the owning link frees the
node at that moment.
Reverse in place
previous = null, current = head
tail = head
while current is not null:
following = current.next # save it before it is overwritten
current.next = previous # flip one arrow
previous = current
current = following
head = previous
Each node is visited once and its arrow flipped once: Θ(n) time, O(1) extra space. The step that
saves following is the one people drop. Without it, flipping current.next cuts the list in two
and the rest is lost.
Costs and assumptions
| Operation | Time | Notes |
|---|---|---|
| prepend | O(1) | Two pointer writes, three on an empty list. |
| append | O(1) | Needs the tail reference; O(n) without it. |
| read the first or last value | O(1) | Through head or tail. |
| find by value, get by index | O(n) | Walks from the head. |
| remove by value | O(n) | The walk dominates; the unlink itself is O(1). |
| remove the head | O(1) | head = head.next. |
| remove the tail | O(n) | You need the node before the tail, and only a walk finds it. |
| insert or remove after a node you already hold | O(1) | This is the real advantage of linked lists. |
| reverse | Θ(n) | O(1) extra space. |
"Linked lists have O(1) insertion" is only true at a position you already have a reference to. Inserting at index 500 still costs 500 steps to get there. If you mostly look things up by index, a dynamic array is better on every count.
Memory and speed. Each node carries at least one extra reference, and in C#, Java and Python it is a separate heap object with its own header. A list of a million small integers can easily take several times the memory of an array of the same values. The nodes are also scattered, so walking them gets little help from the CPU cache. In practice, a dynamic array often beats a linked list even for workloads that look list-friendly on paper. Measure before choosing.
Invariants the implementation keeps
After every public operation:
headis null exactly whentailis null, exactly whencountis 0.- Following
nextfromheadreachestailaftercount - 1steps, andtail.nextis null. - No node is reachable twice (no cycle).
The shared fixture checks these indirectly: reverse-then-append fails if reverse forgets to move
tail, and remove-tail-then-append fails if remove forgets the tail case.
Built-in linked lists
| C# | Python | Java | C++ | |
|---|---|---|---|---|
| Type | LinkedList<T> (doubly linked) |
no linked list type; collections.deque for the ends |
LinkedList<E> (doubly linked) |
std::forward_list<T> (singly), std::list<T> (doubly) |
| Add at the front / back | AddFirst, AddLast |
appendleft, append |
addFirst, addLast |
push_front; std::list also has push_back |
| Insert next to a known node | AddAfter(node, x), AddBefore |
n/a | ListIterator.add |
insert_after(it, x) / insert(it, x) |
| Remove a known node | Remove(node), O(1) |
n/a | ListIterator.remove, O(1) |
erase_after(it) / erase(it) |
| Remove by value | Remove(x), O(n) |
remove(x), O(n) |
remove(Object), O(n) |
remove(x) removes all equal elements |
| Index access | none | d[i], O(n) in the middle |
get(i), walks from the nearer end |
none |
Details that matter:
- C# exposes the nodes themselves (
LinkedListNode<T>withNext,Previous,Value). Keep a node and later insertions or removals around it are O(1).Find(x)returns the first matching node. - Python has no linked list in the standard library. A
listis a dynamic array.dequegives O(1) appends and pops at both ends; the docs describe indexed access as O(1) at the ends and O(n) in the middle. In CPython it is built from linked fixed-size blocks, an implementation detail. If you write your own node class,__slots__(as the teaching version does) saves memory per node. - Java's
LinkedListimplements bothListandDeque. Itsget(i)traverses from the head or the tail, whichever is closer, so a loopfor (i…) list.get(i)is O(n²). Iterate with a for-each loop or an iterator instead. For queue and stack use, the Javadoc ofArrayDequesays it is likely faster. - C++
std::forward_listis the true singly linked list: nosize()member, nopush_back, and insertion and removal happen after an iterator (before_begin()gives a position before the first element).std::listis doubly linked, has O(1)size()since C++11, andsplicemoves nodes from one list to another without copying elements. In both, inserting never invalidates other iterators, and erasing invalidates only iterators to the erased element.
The teaching implementation
The four listings are one design: head, tail, count, prepend, append, index_of, remove
(first occurrence, returns whether something was removed) and reverse. Equality uses the language's
standard comparison: EqualityComparer<T>.Default in C#, Objects.equals in Java, == in Python and
C++. The lab's text view shows remove returning the removed value so the trace is easier to follow;
the code returns a boolean.
The C++ version shows two ownership details. Nodes own their successor through std::unique_ptr
while tail is a plain, non-owning pointer. And the destructor unlinks nodes in a loop: the default
destructor would destroy next, which destroys its next, and so on, one stack frame per node, which
overflows the stack on a long list.
Common mistakes
- Losing the rest of the list by overwriting
nextbefore saving it (reverse) or by movingheadbefore linking the new node (prepend). - Forgetting the empty case. Prepend and append on an empty list must set both
headandtail. - Forgetting the tail on removal when the removed node was the last one.
- Dereferencing null. Every walk must check
currentbefore readingcurrent.nextorcurrent.value. - Calling a list "O(1) insert" without a node in hand. Locating the position is the expensive part.
- Indexing a linked list in a loop, which turns a linear algorithm quadratic.
Edge cases
- Empty list:
findreturns -1 without visiting anything;reversedoes nothing. - One node: it is both head and tail; removing it must make both null.
- Duplicates:
removeandindex_ofact on the first match only (fixtureduplicates). - Value not present: the walk reaches null and reports it; nothing changes.
- Reverse, then append: the old head is the new tail, so the appended node goes after it.
Worked practice
1. Starting empty: append 1, append 2, prepend 0, reverse. What is the list, and which node is the tail?
Answer
Before the reverse the list is 0 → 1 → 2. Reversing gives 2 → 1 → 0, so head is 2 and tail is
the node holding 0, the old head.
2. Why is removing the last node O(n) even though the list keeps a tail reference?
Answer
Removing the tail means setting the second-to-last node's next to null and making it the new tail.
A singly linked node does not know its predecessor, so the only way to find that node is to walk from
the head. A doubly linked list stores prev and can do it in O(1).
3. Suppose reverse forgot the line tail = head. What does append 1, append 2, reverse, append 3 produce?
Answer
After the reverse, tail still refers to node 2, which is now the head. append 3 sets
node2.next = node3, which drops the link to node 1. The list becomes 2 → 3 and node 1 is lost
(and count says 3). That is exactly the bug the fixture case reverse-then-append catches.
4. How can you find the middle node in one pass without knowing the length?
Answer
Walk two pointers from the head: slow moves one node per step, fast moves two. When fast reaches
the end, slow is in the middle. The same fast/slow idea detects a cycle: if the list loops, the fast
pointer eventually lands on the slow one.
Summary
- A linked list is nodes plus
nextreferences;head,tailandcountlive in the list object. - Prepend is O(1); append is O(1) with a tail; find, get by index and removing the tail are O(n).
- Removal needs the previous node; reversal needs a saved
next. Both are about not losing references. - Insertion and removal are O(1) only at a node you already hold.
- Arrays usually win on memory and speed; reach for a linked list when you splice, or insert and remove next to nodes you keep references to.