本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 1 · 本科一年级
15Linked Structures: Lists, Stacks and Queues
An editor keeps the history of a long document as a sequence of a million edits, and the user goes back to the middle of it to insert a forgotten change. In a dynamic array, inserting in the middle moves half a million entries one cell to the right. In a linked list, it changes two pointers. Linked structures give up the array’s direct access to the -th element in exchange for insertions and removals that touch only the neighbours. This chapter builds them in C, puts stacks and queues on top of both kinds of structure behind one interface each, separates the loop over a structure from the structure with iterators, and measures what the table of costs does not say.
You already know
An abstract data type is a set of operations with a specification; its implementations are interchangeable behind its interface (Chapter 14). A pointer holds an address; p->f is the field f of the structure that p points to; a cell obtained from malloc must be returned with free exactly once, and never used afterwards (Chapters 4 and 5).
15.1 Singly linked lists
Definition 15.1 (Linked list, cell)
A linked list stores a sequence in cells, each holding one element and a pointer to the next cell; the last cell’s pointer is null, and the list is given by a pointer to its first cell (null for the empty list). In a singly linked list each cell knows only its successor; in a doubly linked list it also knows its predecessor.
typedef struct node {
int value;
struct node *next; // NULL in the last cell
} node;
Pushing at the front makes a new cell that points to the old first cell, and makes it the first: , whatever the length. Inserting after a known cell is just as cheap: the new cell takes the old successor, and the cell points to the new one. The order of the two assignments matters: done the other way round, the rest of the list would be lost.
Removal is the delicate operation, because the cell before the removed one must be changed, and the first cell has no cell before it: the pointer head itself must change. The usual code has two cases. A pointer to a pointer removes the distinction: link points to the link that leads to the cell under examination, either head or the next field of a cell, and redirecting *link works the same way in both cases.
int list_remove(node **head, int x) {
node **link = head; // the link that points to the cell under examination
while (*link != NULL && (*link)->value != x) link = &(*link)->next;
if (*link == NULL) return 0;
node *dead = *link;
*link = dead->next; // redirect the link past the cell, then free it
free(dead);
return 1;
}
link holds the address of the field that leads to the cell, here the next field of the cell 1, and the field is redirected past the cell. Removing 1 would redirect head the same way.The version with cases needs the cell before the one removed, and therefore a separate branch for the first cell; both versions give the same lists.
int remove_cases(node **head, int x) {
if (*head == NULL) return 0;
if ((*head)->value == x) { // special case: the first cell
node *dead = *head;
*head = dead->next;
free(dead);
return 1;
}
node *prev = *head; // general case: find the cell before
while (prev->next != NULL && prev->next->value != x) prev = prev->next;
if (prev->next == NULL) return 0;
node *dead = prev->next;
prev->next = dead->next;
free(dead);
return 1;
}
2 -> 4 -> NULL
2 -> 4 -> NULL
$ gcc -std=c17 -O2 -Wall -Wextra -o list_demo list_demo.c list.c -lm && ./list_demo
1 -> 2 -> 3 -> 4 -> 5 -> NULL
1 -> 2 -> 25 -> 3 -> 4 -> 5 -> NULL
remove 9: 0
2 -> 25 -> 3 -> 5 -> NULL
length 4
Accessing the -th element, finding a value, and appending at the end without a pointer to the last cell all walk the list: . Freeing a list must read next before freeing the cell that holds it (Exercise 15.5).
15.2 Doubly linked lists and sentinels
A cell that knows its predecessor can be removed in when it is known, with no walk to find the cell before. The four special cases of a doubly linked list — empty list, first cell, last cell, only cell — disappear with one more idea.
Definition 15.2 (Sentinel)
A sentinel is a cell that holds no element and is always present. In a circular doubly linked list with a sentinel, the sentinel’s successor is the first cell, its predecessor the last, and the empty list is the sentinel pointing to itself both ways.
dnode *dlist_insert_after(dnode *cell, int x) {
dnode *n = malloc(sizeof *n);
if (n == NULL) {
perror("dlist");
exit(1);
}
*n = (dnode){x, cell, cell->next};
cell->next->prev = n; // the old neighbour now points back to n
cell->next = n;
return n;
}
void dlist_remove(dnode *cell) {
cell->prev->next = cell->next; // both neighbours always exist
cell->next->prev = cell->prev;
free(cell);
}
Proposition 15.3 (No special case)
In a circular doubly linked list with a sentinel, every cell, the sentinel included, has a predecessor and a successor, and for every cell . Insertion after any cell and removal of any cell other than the sentinel preserve this invariant.
Proof. The empty list satisfies it: the sentinel is its own neighbour both ways. Insertion of after , with : afterwards and backwards, every other link unchanged, so the property holds at , and , and elsewhere as before. Removal of between and links and to each other both ways, which restores the property at both. No step uses a null pointer, because there are none. ∎
$ gcc -std=c17 -O2 -Wall -Wextra -o dlist_demo dlist_demo.c dlist.c -lm && ./dlist_demo
[S] <-> [S]
[S] <-> 1 <-> 2 <-> 3 <-> [S]
[S] <-> 1 <-> 20 <-> 3 <-> [S]
popped 3 at the back and 1 at the front
[S] <-> 20 <-> [S]
15.3 Stacks, queues and deques
Definition 15.4 (Stack, queue, deque)
A stack is an abstract type with operations push, pop, top and empty, where pop removes the element pushed last (last in, first out). A queue has put and take, where take removes the element put first (first in, first out). A deque, or double-ended queue, allows adding and removing at both ends.
Each has an array implementation and a linked one. A stack on a dynamic array pushes and pops at the end, in amortised ; on a singly linked list, at the front, in . A queue on a circular buffer was built in Chapter 14; on a singly linked list it keeps a pointer to each end, takes at the front and puts at the rear. The doubly linked list of the previous section is a deque.
struct queue {
cell *front, *rear; // both NULL when empty; rear->next == NULL otherwise
};
void queue_put(queue *q, int x) {
cell *c = malloc(sizeof *c);
if (c == NULL) exit(1);
*c = (cell){x, NULL};
if (q->rear == NULL) q->front = c; // the queue was empty
else q->rear->next = c;
q->rear = c;
}
int queue_take(queue *q) {
cell *c = q->front;
int x = c->value;
q->front = c->next;
if (q->front == NULL) q->rear = NULL; // the queue is now empty
free(c);
return x;
}
The header stack.h declares an opaque struct stack; stack_array.c and stack_list.c each define it. A bracket checker, a user of the stack, is linked with each and gives the same answers; one test suite, in a header included by two test files, checks both implementations.
$ gcc -std=c17 -O2 -Wall -Wextra brackets.c stack_array.c -o check_array
$ gcc -std=c17 -O2 -Wall -Wextra brackets.c stack_list.c -o check_list
$ ./check_array
stack on an array
a[i] = f(b[j], {c}) balanced
(a + b] error at position 6
((x) error at position 4
x) error at position 1
$ ./check_list
stack on a linked list
a[i] = f(b[j], {c}) balanced
(a + b] error at position 6
((x) error at position 4
x) error at position 1
15.4 Iterators
Summing the elements of an array and of a list are the same loop written twice: for (i = 0; i < n; i++) in one case, for (p = head; p != NULL; p = p->next) in the other. An iterator separates what the loop does from how the structure is walked.
Definition 15.5 (Iterator)
An iterator over a structure is a value that designates a position in it, with an operation that tells whether elements remain and an operation that returns the next element and advances. A loop written with an iterator works on every structure that provides one.
typedef struct { // an iterator: where we are, and how to move on
const node *cell; // for a list
const int *at, *end; // for an array
} iter;
static iter list_begin(const node *head) { return (iter){head, NULL, NULL}; }
static iter array_begin(const int *a, size_t n) { return (iter){NULL, a, a + n}; }
static bool has_next(const iter *it) { return it->cell != NULL || it->at != it->end; }
static int next(iter *it) {
if (it->cell != NULL) {
int x = it->cell->value;
it->cell = it->cell->next;
return x;
}
return *it->at++;
}
static long sum(iter it) { // knows nothing of lists or arrays
long s = 0;
while (has_next(&it)) s += next(&it);
return s;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o iter iter.c list.c -lm && ./iter
sum of the list 10, of the array 60
<1><2><3><4>
The alternative is a callback: the structure provides a function list_each(head, f) that calls f on every element. The iterator lets the caller stop, resume, or walk two structures side by side; the callback keeps the walk inside the structure’s code. Either way, an iterator is valid only while the structure does not change: if the cell an iterator points to is removed, the iterator holds the address of freed memory (Exercise 15.4).
15.5 Costs, by proof and by measurement
| operation | dynamic array | singly linked list | doubly linked list |
|---|---|---|---|
| access the -th element | |||
| add or remove at the front | |||
| add or remove at the end | amortised | to add (rear pointer) | |
| insert after a known position | |||
| remove a known cell | (find the one before) | ||
| memory per element | 1 to 4 cells | element + 1 pointer | element + 2 pointers |
The table counts operations. A traversal of elements is on every structure, and yet:
$ gcc -std=c17 -O2 -Wall -Wextra -o traverse traverse.c -lm && ./traverse
array 0.59 ns per element (sum 8796090925056)
list, cells in order 3.13 ns per element
list, cells shuffled 144.01 ns per element
The three loops perform the same number of additions. The array is read sequentially, and the processor fetches memory in blocks ahead of use; a list whose cells are in order is nearly as regular, with a pointer to follow at each step; the shuffled list sends each step to an unpredictable address, and most of them miss every cache, a factor of about 200. The memory hierarchy behind this is the subject of the second year. A linked structure pays for its flexibility with locality, and its costs in the table are only a part of the story.
Safe use
Every linked structure in C is a set of cells to free exactly once. A cell freed while another pointer still refers to it, or a next field read after its cell was freed, is undefined behaviour that may run correctly for years; the address sanitizer (Chapter 7) catches it in the tests.
15.6 Exercises
Exercise 15.1 ★
Starting from the empty list, draw the list after: push 3, push 8, push 1, insert 5 after the first cell, remove 8, push 2, remove 2.
Solution
Solution of Exercise 15.1.
; ; ; ; ; ; and finally .
Exercise 15.2 ★
A stack and a queue start empty and receive the same operations: add 1, add 2, add 3, remove, add 4, remove, remove. Which elements does each return, and what does each hold at the end?
Exercise 15.3 ★
What does the bracket checker of Output 15.4 report for f(a[0)], {}[]() and ]? Give the stack’s contents at the error.
Exercise 15.4 ★
An iterator over the list has returned 1 and 2. What happens if the cell holding 3 is now removed and the loop continues? And if the cell holding 2 is removed instead?
Solution
Solution of Exercise 15.4.
After returning 2, the iterator points to the cell holding 3, the next to return. Removing that cell frees it, and the next call reads freed memory: undefined behaviour, which may print 3, garbage, or crash. Removing the cell holding 2 is harmless here: the iterator no longer refers to it, and the loop continues with 3 and 4. An iterator is invalidated by any change to the cells it may still reach; most libraries simply forbid changes during an iteration.
Exercise 15.5 ★★
This function frees a list. Read the sanitizer’s report, explain the error, and correct the loop.
void free_all(node *head) {
for (node *p = head; p != NULL; p = p->next) free(p);
}
Solution
Solution of Exercise 15.5.
==1000==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000058 at pc 0x555555555254 bp 0x7fffffffe5a0 sp 0x7fffffffe590
READ of size 8 at 0x502000000058 thread T0
#0 0x555555555253 in free_all exo_free_bug.c:11
#1 0x555555555323 in main exo_free_bug.c:21
SUMMARY: AddressSanitizer: heap-use-after-free exo_free_bug.c:11 in free_all
The increment p = p->next runs after free(p): it reads 8 bytes, the next field, inside a cell of 16 bytes that has just been freed, at line 11. The fix reads the successor first: node *next = p->next; free(p); p = next;, as list_free does in Section 15.1.
Exercise 15.6 ★★
This queue loses its elements after it becomes empty once. Find the case it forgets, state the representation invariant it breaks, and repair it.
void put(int x) {
cell *c = malloc(sizeof *c);
*c = (cell){x, NULL};
if (rear == NULL) front = c;
else rear->next = c;
rear = c;
}
int take(void) {
cell *c = front;
int x = c->value;
front = c->next;
free(c);
return x;
}
int main(void) {
put(1);
printf("took %d\n", take());
put(2);
put(3);
printf("front is %s\n", front == NULL ? "NULL" : "a cell");
return 0;
}
took 1
front is NULL
Solution
Solution of Exercise 15.6.
take does not reset rear when the queue becomes empty. The invariant “front is null exactly when rear is” is broken: after the first take, rear still points to the freed cell, the next put writes into it, and front stays null, so the queue looks empty while it holds 2 and 3. The repair adds if (front == NULL) rear = NULL; after advancing front, as in Listing 15.5.
Exercise 15.7 ★★
Write list_reverse(head), which reverses a singly linked list in place in one pass and returns the new first cell. State its loop invariant, and test it on lists of length 0, 1 and 6.
Solution
Solution of Exercise 15.7.
node *list_reverse(node *head) {
node *done = NULL; // invariant: done is the reversed prefix, head the rest
while (head != NULL) {
node *next = head->next;
head->next = done;
done = head;
head = next;
}
return done;
}
Invariant: done is the reversal of the cells already passed, and head is the rest of the original list; together they hold every cell once. Each turn moves one cell from head to the front of done. At the exit head is null, and done is the whole list reversed. One pass, , no allocation. The test reverses a list of six cells, a list of one and the empty list.
Exercise 15.8 ★★
Write a deque on a circular buffer of fixed capacity: push and pop at both ends in . Test it against the doubly linked list.
Solution
Solution of Exercise 15.8.
typedef struct {
int data[CAP];
size_t head, count; // the deque is data[head], ..., data[(head + count - 1) % CAP]
} deque;
void deque_init(deque *d) { d->head = d->count = 0; }
bool deque_full(const deque *d) { return d->count == CAP; }
void deque_push_back(deque *d, int x) { d->data[(d->head + d->count++) % CAP] = x; }
void deque_push_front(deque *d, int x) {
d->head = (d->head + CAP - 1) % CAP; // one step back, without going negative
d->data[d->head] = x;
d->count++;
}
int deque_pop_front(deque *d) {
int x = d->data[d->head];
d->head = (d->head + 1) % CAP;
d->count--;
return x;
}
Pushing at the front moves the head one step back, written (head + CAP - 1) % CAP so that the unsigned index never goes below zero. The test runs 5000 random operations on this deque and on the sentinel list together, against a plain array model.
Exercise 15.9 ★★
Prove that appends at the end of a singly linked list cost cell visits without a pointer to the last cell, and with one.
Exercise 15.10 ★★★
A list built by mistake may run into a cycle: its last cell points back to an earlier one. Write has_cycle(head), which uses two pointers, one moving one cell at a time and one moving two, and memory. Test it on lists without a cycle and on every cycle of lists up to length 30.
Solution
Solution of Exercise 15.10.
bool has_cycle(const node *head) {
const node *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next; // one step
fast = fast->next->next; // two steps
if (slow == fast) return true;
}
return false; // fast reached the end
}
Without a cycle, fast reaches the end and the function returns false. With one, both pointers end up in the cycle, where the fast one gains one cell per step on the slow one, so it catches it (Exercise 15.11). The test closes lists of every length up to 30 into a cycle at every cell.
Exercise 15.11 ★★★
A list with a cycle has a tail of cells before the cycle and a cycle of cells. Prove that the two pointers of Exercise 15.10 meet after at most steps of the slow pointer.
Solution
Solution of Exercise 15.11.
Number the cells along the list, the cycle being the cells to . After steps the slow pointer is at cell and the fast one at cell (positions read modulo the cycle once past ). For both are in the cycle, and they coincide when , that is when divides . The first meeting is at (at both are at the start): among the consecutive integers there is a multiple of , so they meet after at most steps (exactly when ).
Exercise 15.12 ★★★
A queue can be made of two stacks: put pushes on in; take pops from out, first moving all of in onto out if out is empty. Prove that the queue is correct, and that operations cost pushes and pops in all.
Solution
Solution of Exercise 15.12.
Invariant: the queue, front first, is out from top to bottom followed by in from bottom to top. A put pushes on in, at the rear. A take with out non-empty pops the front. A take with out empty first moves in onto out, which reverses it, so that the oldest element is on top; the invariant is kept. Cost: every element is pushed on in once, moved once (one pop and one push), and popped from out once: at most 4 stack operations per element, so operations cost at most , amortised . A single take can cost . The test checks the order against a model and the bound of 4 per operation along 100 000 random operations.
15.7 Problem: The Josephus circle
Problem 15.1
Weekend problem — The Josephus circle
people, numbered 1 to , stand in a circle. Counting starts at person 1, and every -th person leaves the circle; counting goes on from the next person, until one remains. The problem is named after the historian Flavius Josephus, from a story told about him. A program simulates the circle with a circular linked list, computes the survivor by a recurrence, and compares both with a closed form for .
static int simulate(int n, int k, int show) {
person *people = malloc(n * sizeof *people);
if (people == NULL) return 0; // out of memory: 0 names no one
for (int i = 0; i < n; i++) people[i] = (person){i + 1, &people[(i + 1) % n]};
person *before = &people[n - 1]; // the person before the next one to count
for (int left = n; left > 1; left--) {
for (int step = 1; step < k; step++) before = before->next;
if (show) printf("%d ", before->next->number);
before->next = before->next->next; // the k-th leaves the circle
}
int last = before->number;
free(people);
return last;
}
static int recurrence(int n, int k) { // J(1) = 0, J(n) = (J(n - 1) + k) mod n, from 0
int j = 0;
for (int m = 2; m <= n; m++) j = (j + k) % m;
return j + 1;
}
static int closed_form(int n) { // k = 2: 2(n - 2^floor(log2 n)) + 1
int p = 1;
while (2 * p <= n) p *= 2;
return 2 * (n - p) + 1;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o josephus josephus.c -lm && ./josephus
n = 10, k = 3, leaving: 3 6 9 2 7 1 8 5 10 -> 4 remains
n simulated recurrence closed form
1 1 1 1
2 1 1 1
3 3 3 3
4 1 1 1
5 3 3 3
6 5 5 5
7 7 7 7
8 1 1 1
9 3 3 3
10 5 5 5
11 7 7 7
12 9 9 9
13 11 11 11
14 13 13 13
15 15 15 15
16 1 1 1
k = 2, n <= 10000: simulation and closed form disagree 0 times
k <= 7, n <= 1000: simulation and recurrence disagree 0 times
Part I — Simulation.
- Follow the simulation for , : the departures and the survivor.
- Why does
simulatekeep a pointer to the person before the next one to count? - Why can the cells live in one array, allocated once, although people leave?
- Show that the simulation costs steps.
- What would the cost be with a dynamic array, removing each departing person by shifting the others?
- Why is the circular list, rather than a list with an end, the natural structure here?
Part II — The recurrence.
- Number the people from 0 to , and let be the survivor’s number. Show that the first to leave is .
- After that departure, renumber the remaining people from 0, starting at the person after the one who left. Show that the old number of a person is (new number .
- Deduce and .
- Compute for and check the survivor of the first line of the output (numbered from 1).
- What does the recurrence cost, and why is it so much cheaper than the simulation for large ?
- Check in the output that the recurrence and the simulation agree for and .
Part III — The closed form for .
- With people numbered from 1, show that for , after the first round the people left are , and counting starts again at 1; deduce .
- For , the first round removes and then 1; deduce .
- With , compute for and compare with the table.
- Write with . Prove by strong induction that .
- What is ? Explain it directly with the rounds.
- In binary, show that is rotated left by one bit (the leading 1 moved to the end).
Part IV — Checking.
- The program checks the closed form against the simulation for . Estimate the number of steps.
- Why is a simulation a good oracle here, and what does the check add to the proof?
- An independent test simulates the circle with an array of flags instead of a list. Why test with a second simulation of a different kind?
- For which is the survivor person itself, for ?
- For , how does compare with ? Read it on the table.
- State the named result of the problem, Josephus for , with its proof and its check.
Solution
Solution of Problem 15.1.
1. The departures are 2, 4, 1, 5, and 3 remains.
2. Removing a cell from a singly linked list changes the next field of the cell before it.
3. Nobody is ever freed: a departing cell is only unlinked, and the whole array is freed at the end.
4. Each of the departures follows links: steps, in for .
5. Counting is cheap with indices modulo the size, but each removal shifts up to elements: in the worst case, whatever .
6. Counting goes on past the last person to the first: the circle is the list’s own shape.
7. Counting starts at person 0, and the -th person counted is , modulo .
8. The new person 0 is the old person , the new 1 is old , and so on around the circle.
9. With one person, the survivor is 0. Otherwise the survivor of the circle of is the same person, with new number , hence old number .
10. for : 0, 1, 1, 0, 3, 0, 3, 6, 0, 3; from 1, the survivor of ten people is 4, as printed.
11. steps of constant cost, whatever , against .
12. The last line of the output reports 0 disagreements.
13. The first round removes the even numbers and comes back to 1. The person in position of the new circle is , so .
14. After , counting goes on with 1, the second counted after is 1, which leaves; the circle restarts at 3 with people , position being : .
15. 1, 1, 3, 1, 3, 5, 7, 1, 3, 5, 7, 9, 11, 13, 15, 1, the column of the table.
16. : . For with : , using even. For , is odd and : .
17. 1: each round halves the circle and restarts at person 1, who is never counted second.
18. gives , and .
19. link steps.
20. It follows the definition literally, with no reasoning that could be wrong; the check would catch an error in the proof or in the closed form’s code, for the values tried.
21. Errors in a list simulation and in an array simulation are unlikely to be the same.
22. when , that is : for , such as 1, 3, 7 and 15.
23. , except when is a power of 2, where it falls back to 1.
24. Josephus for : with , , the survivor is , proved from the recurrences of questions 13 and 14 by strong induction, and checked against the simulation for every with no disagreement.