Linked Lists (DSA Core #2)
A linked list trades locality for flexibility: every element is a separate
allocation, and inserting one means changing two pointers instead of shifting a
whole array. In an OA that shows up as pointer surgery, and pointer surgery fails
in exactly three ways — you lose the rest of the list, you dereference nullptr,
or you loop forever.
Nodes and the two layouts
struct ListNode {
int val;
ListNode* next;
ListNode(int v, ListNode* n = nullptr) : val(v), next(n) {}
};
A singly linked list stores next only. A doubly linked list adds prev, which
buys \(O(1)\) deletion when you already hold the node, at the cost of one more
pointer per element and two more updates per operation.
struct DNode {
int val;
DNode *prev, *next;
};
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, minimum width=1.5cm, minimum height=0.72cm, font=\small},
a/.style={->, thick}]
\node[n, fill=blue!10] (x) at (0,0) {1};
\node[n, fill=blue!10] (y) at (2.2,0) {2};
\node[n, fill=blue!10] (z) at (4.4,0) {3};
\draw[a] (x) -- (y);
\draw[a] (y) -- (z);
\node[font=\scriptsize\ttfamily, anchor=west] at (5.1,0) {nullptr};
\draw[a] (z) -- (5.0,0);
\node[font=\scriptsize, text=blue!45!black, anchor=north] at (1.1,-0.55) {next};
\node[font=\scriptsize, anchor=south] at (-0.2,0.45) {head};
\end{tikzpicture}
Nothing here is contiguous, so there is no a[i]. Finding the \(i\)-th element
costs \(i\) pointer hops. Every algorithm below is really an algorithm for walking
without losing your place.
The nullptr terminator is the sentinel that makes traversal stop. A dummy
head is the second useful sentinel: a fake node before the real first node, so
inserting or deleting at the front stops being a special case.
ListNode dummy(0);
dummy.next = head;
ListNode* prev = &dummy; // prev->next is the current node
With the dummy, “delete the head” and “delete the middle” are the same code.
Insertion and deletion
Insert after a known node is three lines. Delete after a known node needs the
previous node, which is why traversal always carries prev.
void insertAfter(ListNode* node, int val) {
node->next = new ListNode(val, node->next); // read old next first
}
void deleteAfter(ListNode* prev) {
ListNode* dead = prev->next;
if (!dead) return;
prev->next = dead->next; // unlink before freeing
delete dead;
}
The order matters. node->next = new ListNode(val); node->next->next = ... loses
the tail. Read next, build the node, then link.
Deleting a value anywhere, with a dummy head:
ListNode* removeValue(ListNode* head, int target) {
ListNode dummy(0);
dummy.next = head;
ListNode* prev = &dummy;
while (prev->next) {
if (prev->next->val == target) {
ListNode* dead = prev->next;
prev->next = dead->next;
delete dead;
} else {
prev = prev->next; // only advance when nothing was removed
}
}
return dummy.next;
}
else is doing real work there. Advancing unconditionally after a deletion skips
the node that just moved into place, so two adjacent targets leave one behind.
In a doubly linked list, deletion given the node is four writes and no traversal:
void unlink(DNode* node) {
if (node->prev) node->prev->next = node->next;
if (node->next) node->next->prev = node->prev;
delete node; // caller must keep head/tail pointers in sync
}
That \(O(1)\) unlink is the reason an LRU cache pairs a hash map with a doubly linked list (Ch. 4).
else instead of always advancing?ASolution
After unlinking, prev->next is a new node that has not been checked. Advancing
would skip it. Without a removal there is nothing new to check, so advance.
Reversal
Three pointers, one pass. prev is the already-reversed part, cur is the node
being moved, nxt saves the rest before the link flips.
ListNode* reverse(ListNode* head) {
ListNode* prev = nullptr;
ListNode* cur = head;
while (cur) {
ListNode* nxt = cur->next; // save before overwriting
cur->next = prev; // flip
prev = cur; // advance
cur = nxt;
}
return prev; // new head
}
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, minimum width=1.2cm, minimum height=0.65cm, font=\small\bfseries},
a/.style={->, thick}]
\node[n, fill=green!22] (p) at (0,0) {1};
\node[n, fill=orange!30] (c) at (1.9,0) {2};
\node[n] (x) at (3.8,0) {3};
\draw[a, green!50!black] (p) -- (0,-0.9) node[below, font=\scriptsize] {prev};
\draw[a] (c) -- (x);
\draw[a, dashed, red!60] (c) -- (p) node[midway, above, font=\scriptsize] {flip};
\draw[a, blue!60] (c) -- (1.9,-0.9) node[below, font=\scriptsize] {cur};
\draw[a] (x) -- (3.8,-1.5) -- (5.6,-1.5) node[right, font=\scriptsize] {nxt saves the tail};
\end{tikzpicture}
The loop invariant: prev points at the head of the reversed prefix, cur at the
head of the untouched suffix, and the two are disconnected except through the
pointer being flipped. Every iteration moves one node from suffix to prefix, so it
terminates after n steps with cur == nullptr and prev at the old tail.
Recursive version, for when the interviewer asks (costs \(O(n)\) stack):
ListNode* reverseRec(ListNode* head) {
if (!head || !head->next) return head;
ListNode* newHead = reverseRec(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
Reversal appears inside bigger problems: reverse in groups of k, reverse between
positions m and n, palindrome check (find middle, reverse second half,
compare), and adding two numbers stored as lists.
nxt be read beforecur->next = prev?
ASolution
Flipping the link destroys the only reference to the rest of the list. Without saving it first, the tail is unreachable.
Fast and slow pointers
Two pointers moving at different speeds give you position and cycle information without knowing the length. Slow moves one node, fast moves two.
Middle node. When fast reaches the end, slow is halfway.
ListNode* middle(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) { // fast->next check is required
slow = slow->next;
fast = fast->next->next;
}
return slow; // second middle for even length
}
Drop fast->next from the condition and odd-length lists null-dereference. For
the first middle, start fast = head->next or stop one step earlier.
\(k\)-th from the end. Move fast \(k\) steps ahead, then walk both until fast hits the end.
ListNode* kthFromEnd(ListNode* head, int k) {
ListNode *fast = head, *slow = head;
for (int i = 0; i < k; ++i) {
if (!fast) return nullptr;
fast = fast->next;
}
while (fast) { slow = slow->next; fast = fast->next; }
return slow;
}
The distance between them is constant at k, so when fast exits, slow is exactly
k from the end.
Cycle detection (Floyd). If there is a cycle, fast laps slow inside it and they meet. If not, fast falls off the end.
bool hasCycle(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
Where the cycle starts. Let a be the distance from the head to the cycle
entry, b the distance from the entry to the meeting point, and L the cycle
length. Slow walked a + b. Fast walked the same distance plus some whole number
of extra laps:
\[ 2(a + b) = a + b + kL \quad\Longrightarrow\quad a + b = kL \quad\Longrightarrow\quad a = kL - b \]
So a and L - b are the same distance modulo L: from the meeting point, L -
b steps forward is the entry, and from the head, a steps forward is the same
entry. Reset one pointer to the head and move both one step at a time; they meet
at the entry, whatever k was.
ListNode* cycleStart(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
slow = head;
while (slow != fast) { slow = slow->next; fast = fast->next; }
return slow;
}
}
return nullptr;
}
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\scriptsize\bfseries},
a/.style={->, thick}]
\node[n] (h) at (0,0) {1};
\node[n] (e) at (1.5,0) {2};
\node[n] (b) at (3.0,0) {3};
\node[n] (c) at (4.5,0) {4};
\node[n] (d) at (3.0,-1.5) {5};
\draw[a] (h) -- (e);
\draw[a] (e) -- (b);
\draw[a] (b) -- (c);
\draw[a] (c) -- (4.5,-1.5) -- (d);
\draw[a] (d) -- (b);
\node[font=\scriptsize, text=blue!60!black, anchor=south] at (0.6,0.1) {a};
\node[font=\scriptsize, text=orange!80!black, anchor=south] at (3.75,0.05) {b};
\node[font=\scriptsize, text=green!45!black, anchor=west] at (4.6,-0.9) {L-b};
\end{tikzpicture}
This is the tortoise-and-hare idea, and it needs no extra memory. The hash-set alternative is \(O(n)\) space and, in an OA, slower for the same answer.
a = L - b?ASolution
Slow traveled a + b, fast traveled a + b + L in the same time and at double
speed. Setting 2(a+b) = a+b+L gives a = L-b.
Merging sorted lists
Two pointers, pick the smaller head, splice. The dummy head removes the “which list starts the result” special case.
ListNode* mergeTwo(ListNode* a, ListNode* b) {
ListNode dummy(0);
ListNode* tail = &dummy;
while (a && b) {
if (a->val <= b->val) { tail->next = a; a = a->next; }
else { tail->next = b; b = b->next; }
tail = tail->next;
}
tail->next = a ? a : b; // attach the remainder, no loop needed
return dummy.next;
}
The leftover attachment is \(O(1)\) and is where people write a pointless while
loop. Since both inputs are already sorted, the rest of the non-empty list is
sorted and larger than everything already placed.
Merging k lists: repeatedly merge pairs (divide and conquer) for
\(O(N \log k)\) with \(N\) total nodes, or use a min-heap of the k heads for the same
bound with a smaller constant when k is large (Ch. 11 in the DSA course).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, minimum width=0.85cm, minimum height=0.6cm, font=\scriptsize\bfseries},
a/.style={->, thick}]
\foreach \v [count=\i from 0] in {1,4,7} \node[n, fill=blue!12] at (\i*1.0,0.8) {\v};
\foreach \v [count=\i from 0] in {2,3,9} \node[n, fill=orange!18] at (\i*1.0,0) {\v};
\foreach \v [count=\i from 0] in {1,2,3,4,7,9} \node[n, fill=green!18] at (\i*1.0,-1.0) {\v};
\node[font=\scriptsize, anchor=east] at (-0.6,0.8) {a};
\node[font=\scriptsize, anchor=east] at (-0.6,0) {b};
\node[font=\scriptsize, anchor=east] at (-0.6,-1.0) {out};
\end{tikzpicture}
assignment enough to finish the merge?
ASolution
The remaining list is already sorted and every one of its values is at least as large as the last value placed, so it can be attached whole.
Linked list versus array
Array / vector |
Linked list | |
|---|---|---|
| Index access | \(O(1)\) | \(O(n)\) |
| Insert/delete at front | \(O(n)\) | \(O(1)\) |
| Insert/delete given a node | \(O(n)\) to find it | \(O(1)\) |
| Memory per element | 4 bytes for int |
4 + 8 (or 16) + allocator header |
| Locality | contiguous, cache-friendly | scattered, one cache miss per node |
| Extra space for algorithms | none | pointers, sometimes recursion |
The cache line is the part people forget. A modern CPU pulls 64 bytes per miss,
so a scan over a vector<int> reads 16 elements per miss, while a linked list
pays a miss per node. Measured, a vector traversal is often 5–10× faster even
though both are \(O(n)\). That is why std::list is rarely the right container in
practice, and why interviewers still ask about it — the pointer manipulation is
the point, not the performance.
Use a list when you need \(O(1)\) splicing with a stable node address (LRU caches, free lists, intrusive lists in kernels). Use a vector for everything else.
In C++, std::list is a doubly linked list with splice, merge, and
sort (member sort, because std::sort needs random access). For OA problems the
input is usually a hand-rolled ListNode*, so know both.
std::sort sort a std::list?ASolution
It requires random-access iterators for its partitioning. std::list provides
bidirectional iterators, so it has its own \(O(n \log n)\) member sort.
Bugs and edge cases
- Losing the tail. Overwriting
cur->nextbefore saving it. Save first, always. nullptrdereference.fast->next->nextwithout checkingfast->next. The loop condition must befast && fast->next.- Empty list.
head->valonnullptr. Return early; most functions should handlehead == nullptrin the first line. - One node. Reversal, middle, and merge all have a one-node path that skips the loop. Trace it.
- Two nodes. The cycle check needs the
fast->nextguard; reversal needsnxtto be non-null on the second step. - Dummy node lifetime. A stack-allocated dummy is fine as long as you return
dummy.next, never&dummy. - Double free / leak. Unlink before
delete, and never delete a node still reachable from the list. - Modifying the list while traversing it. Keep
nxtbefore any relink.
likely cause?
ASolution
The loop condition or the leftover attachment: either the loop stops one node
early (while (a->next && b->next)), or tail->next is never set to the
remaining list after the loop.
Next: Stacks, Queues and Deques (DSA Core #3) — LIFO, FIFO, and the monotonic trick that turns \(O(n^2)\) scans into one pass.