Kodewick
Start learning →
Patterns: arrays and linked lists12 / 52

Patterns: arrays and linked lists

Lesson 12 of 52 · Part 2 · Arrays and linked lists · about 20 minutes

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 oftenChooseWhy
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 havelinked list (list)O(1); an array list moves elements
Don't know how many in advanceeither: vector grows by itselfa linked list news each node, vector is amortised O(1)
Memory matters, cache-friendlyarray listno 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.

Choose one

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?

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 tail pointer remembers the last node and each new one goes after it. The order stays.
L↓
dummyh
3c
2b
1a
nullptr

Head insertion: every new node goes right after the dummy, pushing earlier ones back: read 1 2 3 and you get 3 2 1
L↓tail↓
dummyh
1a
2b
3c
nullptr

Inserting at the tail: tail always points at the last node, each new node goes after it, order unchanged
main.cpp
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}
Output
5 4 3 2 1 
1 2 3 4 5 
Guess the outputA wrong guess is fine

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}

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.

Merging a (1 4 6, green) and b (2 3 8, blue): each node drops to its place in the merged list below, its colour showing which list it came from; dummy at the front is the fake head node, and dummy.next is returned
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.

Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 1

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.

It should print
1 2 3 4 6 8 9
exercise1.cpp
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}
Output
Press Run or Ctrl+Enter

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↓
1a
2b
3c
nullptr
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;

Reversing 1 → 2 → 3: each round, save the next one in next, make cur point back at prev, then prev and cur both step forward

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 in orderDrag, or use the arrows

Put the 4 lines inside the loop in order so the program reverses 1 2 3 4 into 4 3 2 1.

  1. prev = cur;
  2. cur = next;
  3. cur->next = prev;
  4. Node* next = cur->next;
Should print
4 3 2 1
Exercise 2

Reverse in place

Complete reverse_list: reverse the list in place with three pointers and return the new head.

It should print
4 3 2 1
exercise2.cpp
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}
Output
Press Run or Ctrl+Enter

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↓
1a
2b
3c
4d
5e
nullptr

Fast and slow pointers: fast takes two steps, slow one; when fast reaches the end, slow is in the middle

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↓
1a
2b
3c
4d
5e
nullptr

Detecting a cycle: 5 points back to 3; slow takes 1 step, fast 2, and inside the loop fast closes in by 1 each round, so it must catch up
main.cpp
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}
Output
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).

PatternUsed forTimeExtra space
Dummy node + tailbuilding at the tail, merging sorted lists, removing the firstO(n)O(1)
Three pointers reversingreversing a list, palindrome list (reverse the second half)O(n)O(1)
Fast and slow pointersmiddle node, cycle, n-th from the endO(n)O(1)
Choose one

Checking for a cycle with fast and slow pointers: what are the time and the extra space?

Exercise 3

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.

It should print
1 0
exercise3.cpp
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}
Output
Press Run or Ctrl+Enter

With the STL

On std::list these problems have ready-made member functions, all of which change only pointers and copy no elements:

main.cpp
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}
Output
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
Tasklistvector
Merge two sorted onesa.merge(b): O(n), pointers onlystd::merge into a new vector: O(n), O(n) space
Reversea.reverse(): O(n)std::reverse(v.begin(), v.end()): O(n)
Sorta.sort(): O(n log n); std::sort does not workstd::sort: O(n log n)
Find the middlefast 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.

Choose one

list<int> c = {5, 1, 4, 2}; should be sorted small to large. Which line does it?

Summary

Take-away

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.

Guess the outputA wrong guess is fine

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}
Guess the outputA wrong guess is fine

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}
Guess the outputA wrong guess is fine

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}
Guess the outputA wrong guess is fine

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}
Guess the outputA wrong guess is fine

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}