Patterns: arrays and linked lists
This review of arrays and linked lists covers three patterns, all O(n) time and O(1) extra space: a dummy node plus a tail pointer, in-place reversal with prev, cur and next, and fast and slow pointers for the middle or a cycle.
After array lists and linked lists, the questions that come up most in exams and interviews are these: building a list, merging two sorted lists, reversing a list, finding the middle node, detecting a cycle, removing the n-th from the end… Most of them come down to three patterns: a dummy node plus a tail pointer; three pointers turning each next around as they walk; fast and slow pointers, one taking one step and the other two. All three are O(n) time and O(1) extra space. First, a multiple-choice question that comes up nearly every time.
First, choose: array list or linked list
Ask yourself: what does this data do most often?
| Done most often | Choose | Why |
|---|---|---|
| Get by position (the i-th) | array list (vector) | O(1); a linked list walks i steps |
| Insert or delete next to a node you have | linked list (list) | O(1); an array list moves elements |
| Don't know how many in advance | either: vector grows by itself | a linked list news each node, vector is amortised O(1) |
| Memory matters, cache-friendly | array list | no pointers to store, contiguous memory reads fast |
Common trap: "linked list insert is O(1)" assumes you already have the node before it; "insert at position i" is O(n) for both: the array list is slow at moving, the linked list at finding.
You store a whole class’s scores. The most common job is "look up student i’s score", and you almost never insert or delete. Which do you pick?
a[i] computes the address directly, O(1); a linked list walks i steps from the head, O(n). With almost no inserts or deletes, the linked list’s strength never comes into play.Pattern 1: a dummy node + tail
Reading 1 2 3 4 5 into a linked list can be done two ways:
- Insert at the head: each new node goes right after the dummy node (at the front). The list comes out reversed: 5 4 3 2 1.
- Insert at the tail: a
tailpointer remembers the last node and each new one goes after it. The order stays.
L↓L↓tail↓1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10void show(Node* head) {11 for (Node* p = head; p != nullptr; p = p->next)12 cout << p->val << " ";13 cout << "\n";14}15 16void clear(Node* head) {17 while (head != nullptr) {18 Node* next = head->next;19 delete head;20 head = next;21 }22}23 24int main() {25 // insert at the head: right after the dummy node26 Node* A = new Node(0);27 for (int x = 1; x <= 5; x++)28 A->next = new Node(x, A->next);29 show(A->next);30 31 // insert at the tail: after tail32 Node* B = new Node(0);33 Node* tail = B;34 for (int x = 1; x <= 5; x++) {35 tail->next = new Node(x);36 tail = tail->next;37 }38 show(B->next);39 clear(A);40 clear(B);41 return 0;42}
5 4 3 2 1 1 2 3 4 5
Tail insertion, but tail never moves. What does this print?
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int main() {11 Node* L = new Node(0);12 Node* tail = L;13 for (int x = 1; x <= 3; x++)14 tail->next = new Node(x);15 for (Node* p = L->next; p != nullptr; p = p->next)16 cout << p->val << " ";17 cout << "\n";18 return 0;19}
tail stays on the dummy head, so every pass does L->next = new node and the newest one replaces the one before: only 3 is left (and 1 and 2 are leaked). Tail insertion needs tail = tail->next; after every node.Pattern 1, again: merging two sorted lists
A dummy node and a tail also merge two sorted lists: two lists sorted small to large become one that is still sorted. Put down a dummy node and a tail: each time compare the first of each side and hook the smaller one after tail; when one side is empty, hook on the whole rest of the other.
1Node dummy(0); // a dummy node on the stack, gone when the function returns2Node* tail = &dummy;3while (a != nullptr && b != nullptr) {4 if (a->val <= b->val) { tail->next = a; a = a->next; }5 else { tail->next = b; b = b->next; }6 tail = tail->next;7}8tail->next = (a != nullptr) ? a : b; // hook on the whole rest9return dummy.next;
The dummy node lives on the stack (Node dummy(0);), with no new and no delete. With it, the first node needs no special case; not one node is newed, the old nodes are just linked up again.
When the loop stops, one side has run out. The last line hooks up whatever is left of the other side in one go: what goes in the blank? The program should print 1 2 3 4 6 8 9.
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10Node* merge(Node* a, Node* b) {11 Node dummy(0);12 Node* tail = &dummy;13 while (a != nullptr && b != nullptr) {14 if (a->val <= b->val) {15 tail->next = a;16 a = a->next;17 } else {18 tail->next = b;19 b = b->next;20 }21 tail = tail->next;22 }23 tail->next = ;24 return dummy.next;25}26 27int main() {28 Node* a = new Node(1, new Node(4, new Node(8, new Node(9))));29 Node* b = new Node(2, new Node(3, new Node(6)));30 for (Node* p = merge(a, b); p != nullptr; p = p->next)31 cout << p->val << " ";32 cout << "\n";33 return 0;34}
b or nullptr would drop 8 9.Merge two sorted lists
✓Complete merge_lists: with a dummy node on the stack and a tail, merge two lists sorted small to large into one.
1 2 3 4 6 8 9
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10void show(Node* head) {11 for (Node* p = head; p != nullptr; p = p->next)12 cout << p->val << " ";13 cout << "\n";14}15 16void clear(Node* head) {17 while (head != nullptr) {18 Node* next = head->next;19 delete head;20 head = next;21 }22}23 24Node* merge_lists(Node* a, Node* b) {25 Node dummy(0);26 Node* tail = &dummy;27 // while both have nodes: hook the smaller after tail; then hook on the whole rest28 return dummy.next;29}30 31int main() {32 Node* a = new Node(1, new Node(4, new Node(6)));33 Node* b = new Node(2, new Node(3, new Node(8, new Node(9))));34 Node* m = merge_lists(a, b);35 show(m);36 clear(m);37 return 0;38}
Pattern 2: reversing in place
Turn 1 → 2 → 3 into 3 → 2 → 1 without extra memory. The pattern is three pointers: prev is the head of the part already reversed, cur is the one being handled, and next saves cur's next one first. Save, then turn around: once cur->next changes, only next still points at the old next one.
prev↓cur↓next↓1Node* prev = nullptr;2Node* cur = head;3while (cur != nullptr) {4 Node* next = cur->next;5 cur->next = prev;6 prev = cur;7 cur = next;8}9head = prev;
Each node is touched once: O(n) time, O(1) space. Forget next, write cur->next = prev; then cur = cur->next;, and cur goes back to prev, losing every node after it. Another way is to take the nodes off one by one and insert each at the head after a new dummy node: inserting at the head comes out reversed anyway.
Put the 4 lines inside the loop in order so the program reverses 1 2 3 4 into 4 3 2 1.
prev = cur;cur = next;cur->next = prev;Node* next = cur->next;
4 3 2 1
prev = cur; after cur = next; and prev lands on the wrong node.Reverse in place
✓Complete reverse_list: reverse the list in place with three pointers and return the new head.
4 3 2 1
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10void show(Node* head) {11 for (Node* p = head; p != nullptr; p = p->next)12 cout << p->val << " ";13 cout << "\n";14}15 16void clear(Node* head) {17 while (head != nullptr) {18 Node* next = head->next;19 delete head;20 head = next;21 }22}23 24Node* reverse_list(Node* head) {25 Node* prev = nullptr;26 Node* cur = head;27 // save the next one, turn around, move both forward28 return prev;29}30 31int main() {32 Node* head = new Node(1, new Node(2, new Node(3, new Node(4))));33 head = reverse_list(head);34 show(head);35 clear(head);36 return 0;37}
Pattern 3: fast and slow pointers
A linked list does not know its length and has no index. Let slow take 1 step and fast 2 steps each time: when fast reaches the end, slow is right in the middle.
slow↓fast↓The same pattern detects a cycle: if the list points back somewhere earlier, fast never reaches nullptr; once both are in the loop, fast gains 1 step on slow each round and the gap shrinks by 1 each round, so it is sure to catch up (the two pointers become equal).
slow↓fast↓1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10void show(Node* head) {11 for (Node* p = head; p != nullptr; p = p->next)12 cout << p->val << " ";13 cout << "\n";14}15 16void clear(Node* head) {17 while (head != nullptr) {18 Node* next = head->next;19 delete head;20 head = next;21 }22}23 24Node* middle(Node* head) {25 Node* slow = head;26 Node* fast = head;27 while (fast != nullptr && fast->next != nullptr) {28 slow = slow->next;29 fast = fast->next->next;30 }31 return slow;32}33 34bool has_cycle(Node* head) {35 Node* slow = head;36 Node* fast = head;37 while (fast != nullptr && fast->next != nullptr) {38 slow = slow->next;39 fast = fast->next->next;40 if (slow == fast) // compares addresses: the same node41 return true;42 }43 return false;44}45 46int main() {47 Node* e = new Node(5);48 Node* c = new Node(3, new Node(4, e));49 Node* head = new Node(1, new Node(2, c));50 cout << "the middle is " << middle(head)->val << "\n";51 cout << has_cycle(head) << "\n";52 e->next = c; // 5 points back to 3: a cycle53 cout << has_cycle(head) << "\n";54 e->next = nullptr; // break the cycle first, then delete55 clear(head);56 return 0;57}
the middle is 3 0 1
With an even number of nodes this version stops at the second of the two middle ones; for the first, change the condition to fast->next != nullptr && fast->next->next != nullptr. A variant, "remove the n-th from the end": fast goes n steps ahead, then both move together, and when fast is on the last node, slow is just before the n-th from the end (starting from a dummy node, removing the first node needs no special case).
| Pattern | Used for | Time | Extra space |
|---|---|---|---|
| Dummy node + tail | building at the tail, merging sorted lists, removing the first | O(n) | O(1) |
| Three pointers reversing | reversing a list, palindrome list (reverse the second half) | O(n) | O(1) |
| Fast and slow pointers | middle node, cycle, n-th from the end | O(n) | O(1) |
Checking for a cycle with fast and slow pointers: what are the time and the extra space?
Is there a cycle
✓Complete has_cycle: use fast and slow pointers to tell whether the list has a cycle; return true if it does, false if not.
1 0
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10void show(Node* head) {11 for (Node* p = head; p != nullptr; p = p->next)12 cout << p->val << " ";13 cout << "\n";14}15 16void clear(Node* head) {17 while (head != nullptr) {18 Node* next = head->next;19 delete head;20 head = next;21 }22}23 24bool has_cycle(Node* head) {25 Node* slow = head;26 Node* fast = head;27 // while fast can, it takes two steps and slow one; equal means a cycle28 return false;29}30 31int main() {32 Node* c = new Node(3);33 Node* a = new Node(1, new Node(2, c));34 Node* x = new Node(7, new Node(8, new Node(9)));35 c->next = a->next; // 3 points back to 2: a cycle36 cout << has_cycle(a) << " " << has_cycle(x) << "\n";37 c->next = nullptr; // break the cycle, then delete38 clear(a);39 clear(x);40 return 0;41}
With the STL
On std::list these problems have ready-made member functions, all of which change only pointers and copy no elements:
1#include <iostream>2#include <list>3#include <vector>4#include <algorithm>5using namespace std;6 7void show(const list<int>& lst) {8 for (int x : lst)9 cout << x << " ";10 cout << "\n";11}12 13int main() {14 list<int> a = {1, 4, 6};15 list<int> b = {2, 3, 8, 9};16 a.merge(b); // merge two sorted lists: O(n), b ends up empty17 show(a);18 cout << b.size() << "\n";19 20 a.reverse(); // reverse in place: O(n)21 show(a);22 23 list<int> c = {5, 1, 4, 2};24 c.sort(); // list uses its own sort (merge sort)25 show(c);26 27 vector<int> v = {1, 2, 3, 4, 5};28 reverse(v.begin(), v.end()); // vector: swap from both ends inward29 for (int x : v)30 cout << x << " ";31 cout << "\n";32 cout << v[v.size() / 2] << "\n"; // middle of a vector: O(1)33 return 0;34}
1 2 3 4 6 8 9 0 9 8 6 4 3 2 1 1 2 4 5 5 4 3 2 1 3
| Task | list | vector |
|---|---|---|
| Merge two sorted ones | a.merge(b): O(n), pointers only | std::merge into a new vector: O(n), O(n) space |
| Reverse | a.reverse(): O(n) | std::reverse(v.begin(), v.end()): O(n) |
| Sort | a.sort(): O(n log n); std::sort does not work | std::sort: O(n log n) |
| Find the middle | fast and slow pointers or count: O(n) | v[v.size() / 2]: O(1) |
std::sort needs to jump by index (random-access iterators), and a list iterator only moves one step at a time, so sort(lst.begin(), lst.end()) does not compile: write lst.sort().
In interviews: for a linked-list problem, draw 3 or 4 nodes on paper and every step's arrows before writing code; afterwards, walk through it with an empty list, one node and two nodes. The problem hands you a ListNode* and wants hand-written pointers; std::list is only for checking your answer. For problems that may touch the first node, like deleting or merging, start with a dummy node.
list<int> c = {5, 1, 4, 2}; should be sorted small to large. Which line does it?
std::sort needs to jump by index (random-access iterators), and a list’s iterators can only step one at a time, so the second line doesn’t compile. list has its own sort member (a merge sort that only relinks pointers), O(n log n). merge joins two lists that are already sorted.Summary
Three patterns for array lists and linked lists
- Choosing: vector to get by position, list for frequent inserts and deletes at a known spot
- Dummy node + tail: building at the tail, merging sorted lists; the first node is no longer special
- Reversing: three pointers prev, cur, next; save, then turn around
- Fast and slow pointers: the middle, a cycle, the n-th from the end
1Node dummy(0); Node* tail = &dummy;2next = cur->next; cur->next = prev; prev = cur; cur = next;3slow = slow->next; fast = fast->next->next;
Chapter 1 quick check
5 questions on this chapter: pointers and references, arrays, vector capacity and linked lists. Work out what each prints before you pick.
Changing one by value, one by reference and one through a pointer: what does it print?
1#include <iostream>2using namespace std;3 4void f(int x) { x = 10; }5void g(int& x) { x = 20; }6void h(int* p) { *p = 30; }7 8int main() {9 int a = 1, b = 1, c = 1;10 f(a);11 g(b);12 h(&c);13 cout << a << " " << b << " " << c << "\n";14 return 0;15}
f gets a copy of a, and changing the copy leaves a alone; g's int& x is b itself; h gets c's address, and *p = 30 changes c. So only a is still 1.Inserting 9 at index 2 of an array of length 6: what does it print?
1#include <iostream>2using namespace std;3 4int main() {5 int a[8] = {1, 2, 3, 4, 5, 6};6 int len = 6, pos = 2, moves = 0;7 for (int i = len; i > pos; i--) {8 a[i] = a[i - 1];9 moves++;10 }11 a[pos] = 9;12 len++;13 cout << moves << " " << a[3] << "\n";14 return 0;15}
a[3] is 3.Compiled with g++, an empty vector gets 9 push_backs: what are size and capacity?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> v;7 for (int x = 0; x < 9; x++)8 v.push_back(x);9 cout << v.size() << " " << v.capacity() << "\n";10 return 0;11}
p is the second node; deleting the one after p, what does it print?
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int main() {11 Node* head = new Node(1, new Node(2, new Node(3, new Node(4))));12 Node* p = head->next;13 Node* gone = p->next;14 p->next = gone->next;15 delete gone;16 for (Node* q = head; q != nullptr; q = q->next)17 cout << q->val << " ";18 cout << "\n";19 while (head != nullptr) {20 Node* next = head->next;21 delete head;22 head = next;23 }24 return 0;25}
gone is the 3 after it; p's next becomes 4, then delete gone. What is deleted is the one after p, not p itself.6 nodes, 1 to 6: where does slow point when the fast and slow pointers stop?
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int main() {11 Node* head = nullptr;12 for (int x = 6; x >= 1; x--)13 head = new Node(x, head);14 Node* slow = head;15 Node* fast = head;16 while (fast != nullptr && fast->next != nullptr) {17 slow = slow->next;18 fast = fast->next->next;19 }20 cout << slow->val << "\n";21 while (head != nullptr) {22 Node* next = head->next;23 delete head;24 head = next;25 }26 return 0;27}
fast->next != nullptr && fast->next->next != nullptr.