---
title: "Linked Structures: Lists, Stacks and Queues"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 15
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 15 — Linked 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](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-dynamic-array), inserting in the middle moves half a million entries one cell to the right. In a [linked list](#def-b1-linked-structures-list), it changes two [pointers](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer). Linked structures give up the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array)’s direct access to the $i$-th element in exchange for insertions and removals that touch only the neighbours. This chapter builds them in C, puts [stacks](#def-b1-linked-structures-stack) and [queues](#def-b1-linked-structures-stack) on top of both kinds of structure behind one interface each, separates the loop over a structure from the structure with [iterators](#def-b1-linked-structures-iterator), and measures what the table of costs does not say.

**You already know.**

An [abstract data type](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-adt) is a set of operations with a specification; its implementations are interchangeable behind its interface ([Chapter 14](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#ch-b1-dynamic-arrays)). A [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#ch-b1-pointers-and-arrays) and [5](https://one-course.com/books/computer-science/3/en/chapter/5-dynamic-memory#ch-b1-dynamic-memory)).

## 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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to the next cell; the last cell’s [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) is null, and the list is given by a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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.

```cpp
typedef struct node {
    int value;
    struct node *next;  // NULL in the last cell
} node;
```

***Listing 15.1.** The cell code/bachelor-1/15-linked-structures/listings/list.h*

Pushing at the front makes a new cell that points to the old first cell, and makes it the first: $\Theta(1)$, 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.

![A singly linked list 1, 2, 3, and the insertion of 25 after the cell holding 2: first the new cell points to the successor, then the cell points to the new one; the dashed link is the one replaced.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-linked-structures/fig-37df9ac063c4.svg)

*A [singly linked list](#def-b1-linked-structures-list) $1, 2, 3$, and the insertion of 25 after the cell holding 2: first the new cell points to the successor, then the cell points to the new one; the dashed link is the one replaced.*

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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) `head` itself must change. The usual code has two cases. A [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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.

```c
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;
}
```

***Listing 15.2.** Removal through a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to a link code/bachelor-1/15-linked-structures/listings/list.c*

![Removing 2 with a pointer to a link: 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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-linked-structures/fig-c17d890ae080.svg)

*Removing 2 with a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to a link: `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.

```c
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;
}
```

***Listing 15.3.** Removal with a special case for the first cell code/bachelor-1/15-linked-structures/listings/remove_pp.c*

```
2 -> 4 -> NULL
2 -> 4 -> NULL
```

***Output 15.1.** The list $1, 2, 3, 4$ after removing 1, 3 and the absent 5, by each version. Some lines are left out.*

```
$ 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
```

***Output 15.2.** Pushes, an insertion after the second cell, and removals, the first of the first cell.*

Accessing the $i$-th element, finding a value, and appending at the end without a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to the last cell all walk the list: $\Theta(n)$. Freeing a list must read `next` before freeing the cell that holds it ([Exercise 15.5](#exo-b1-linked-structures-5)).

## 15.2 Doubly linked lists and sentinels

A cell that knows its predecessor can be removed in $\Theta(1)$ when it is known, with no walk to find the cell before. The four special cases of a [doubly linked list](#def-b1-linked-structures-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](#def-b1-linked-structures-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.

```c
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);
}
```

***Listing 15.4.** Insertion and removal with no special case code/bachelor-1/15-linked-structures/listings/dlist.c*

**Proposition 15.3 (No special case).**

In a circular [doubly linked list](#def-b1-linked-structures-list) with a [sentinel](#def-b1-linked-structures-sentinel), every cell, the [sentinel](#def-b1-linked-structures-sentinel) included, has a predecessor and a successor, and $c\text{->next->prev} = c = c\text{->prev->next}$ for every cell $c$. Insertion after any cell and removal of any cell other than the [sentinel](#def-b1-linked-structures-sentinel) preserve this invariant.

**Proof.** The empty list satisfies it: the [sentinel](#def-b1-linked-structures-sentinel) is its own neighbour both ways. Insertion of $n$ after $c$, with $d =
c\text{->next}$: afterwards $c \to n \to d$ and $d \to n \to c$ backwards, every other link unchanged, so the property holds at $c$, $n$ and $d$, and elsewhere as before. Removal of $c$ between $p$ and $d$ links $p$ and $d$ to each other both ways, which restores the property at both. No step uses a [null pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-null), because there are none. ∎

![A circular doubly linked list with a sentinel S, empty and holding 1, 2, 3. Every cell has two neighbours, so insertion and removal never test for an end.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-linked-structures/fig-b33ffb44deab.svg)

*A circular [doubly linked list](#def-b1-linked-structures-list) with a [sentinel](#def-b1-linked-structures-sentinel) S, empty and holding 1, 2, 3. Every cell has two neighbours, so insertion and removal never test for an end.*

```
$ 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]
```

***Output 15.3.** Pushes at both ends, a removal of a known cell, and pops at both ends.*

## 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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) implementation and a linked one. A [stack](#def-b1-linked-structures-stack) on a [dynamic array](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-dynamic-array) pushes and pops at the end, in amortised $\Theta(1)$; on a [singly linked list](#def-b1-linked-structures-list), at the front, in $\Theta(1)$. A [queue](#def-b1-linked-structures-stack) on a [circular buffer](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-ring) was built in [Chapter 14](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#ch-b1-dynamic-arrays); on a [singly linked list](#def-b1-linked-structures-list) it keeps a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to each end, takes at the front and puts at the rear. The [doubly linked list](#def-b1-linked-structures-list) of the previous section is a [deque](#def-b1-linked-structures-stack).

```c
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;
}
```

***Listing 15.5.** A [queue](#def-b1-linked-structures-stack) on a [linked list](#def-b1-linked-structures-list) with a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to each end code/bachelor-1/15-linked-structures/listings/queue_list.c*

![Stacks and queues on arrays and on links. The stack 7, 2, 5 (5 on top) and the queue 4, 6, 8, 9 (4 at the front) each have two representations with the same operations and the same results.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-linked-structures/fig-a8713dcfcaf2.svg)

*[Stacks](#def-b1-linked-structures-stack) and [queues](#def-b1-linked-structures-stack) on [arrays](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) and on links. The [stack](#def-b1-linked-structures-stack) 7, 2, 5 (5 on top) and the [queue](#def-b1-linked-structures-stack) 4, 6, 8, 9 (4 at the front) each have two representations with the same operations and the same results.*

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](#def-b1-linked-structures-stack), is linked with each and gives the same answers; one [test suite](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#def-b1-c-modules-make-tests-unit-test), 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
```

***Output 15.4.** The bracket checker linked with the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) [stack](#def-b1-linked-structures-stack) and with the linked [stack](#def-b1-linked-structures-stack).*

## 15.4 Iterators

Summing the elements of an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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](#def-b1-linked-structures-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.

```c
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;
}
```

***Listing 15.6.** One [iterator](#def-b1-linked-structures-iterator) type for lists and [arrays](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), and a sum that uses only it code/bachelor-1/15-linked-structures/listings/iter.c*

```
$ 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>
```

***Output 15.5.** The same sum on both structures, and the callback style.*

The alternative is a *callback*: the structure provides a function `list_each(head, f)` that calls `f` on every element. The [iterator](#def-b1-linked-structures-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](#def-b1-linked-structures-iterator) is valid only while the structure does not change: if the cell an [iterator](#def-b1-linked-structures-iterator) points to is removed, the [iterator](#def-b1-linked-structures-iterator) holds the address of freed memory ([Exercise 15.4](#exo-b1-linked-structures-4)).

## 15.5 Costs, by proof and by measurement

| operation | [dynamic array](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-dynamic-array) | [singly linked list](#def-b1-linked-structures-list) | [doubly linked list](#def-b1-linked-structures-list) |
| --- | --- | --- | --- |
| access the $i$-th element | $\Theta(1)$ | $\Theta(i)$ | $\Theta(i)$ |
| add or remove at the front | $\Theta(n)$ | $\Theta(1)$ | $\Theta(1)$ |
| add or remove at the end | amortised $\Theta(1)$ | $\Theta(1)$ to add (rear [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer)) | $\Theta(1)$ |
| insert after a known position | $\Theta(n)$ | $\Theta(1)$ | $\Theta(1)$ |
| remove a known cell | $\Theta(n)$ | $\Theta(n)$ (find the one before) | $\Theta(1)$ |
| memory per element | 1 to 4 cells | element + 1 [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) | element + 2 [pointers](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) |

The table counts operations. A traversal of $n$ elements is $\Theta(n)$ 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
```

***Output 15.6.** Summing $2^{22}$ integers on the author’s laptop: in an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), in a list whose [cells](#def-b1-linked-structures-list) follow each other in memory, and in the same list after shuffling the order of its [cells](#def-b1-linked-structures-list).*

The three loops perform the same number of additions. The [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) is read sequentially, and the processor fetches memory in blocks ahead of use; a list whose [cells](#def-b1-linked-structures-list) are in order is nearly as regular, with a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-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](#def-b1-linked-structures-list) to free exactly once. A cell freed while another [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) still refers to it, or a `next` field read after its cell was freed, is [undefined behaviour](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-ub) that may run correctly for years; the address sanitizer ([Chapter 7](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#ch-b1-c-modules-make-tests)) 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 of Exercise 15.1.**

$3$; $8, 3$; $1, 8, 3$; $1, 5, 8, 3$; $1, 5, 3$; $2, 1, 5, 3$; and finally $1, 5, 3$.

**Exercise 15.2 ★.**

A [stack](#def-b1-linked-structures-stack) and a [queue](#def-b1-linked-structures-stack) 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?

**Solution of Exercise 15.2.**

The [stack](#def-b1-linked-structures-stack) returns 3, 4 and 2, and holds 1. The [queue](#def-b1-linked-structures-stack) returns 1, 2 and 3, and holds 4.

**Exercise 15.3 ★.**

What does the bracket checker of [Output 15.4](#out-b1-linked-structures-both) report for `f(a[0)]`, `{}[]()` and `]`? Give the [stack](#def-b1-linked-structures-stack)’s contents at the error.

**Solution of Exercise 15.3.**

`f(a[0)]`: `(` and `[` are pushed; at position 5, `)` pops `[`: error at position 5, with `(` left on the [stack](#def-b1-linked-structures-stack). `{}[]()` is balanced. `]`: error at position 0, on the empty [stack](#def-b1-linked-structures-stack).

**Exercise 15.4 ★.**

An [iterator](#def-b1-linked-structures-iterator) over the list $1, 2, 3, 4$ 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 of Exercise 15.4.**

After returning 2, the [iterator](#def-b1-linked-structures-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](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-ub), which may print 3, garbage, or crash. Removing the cell holding 2 is harmless here: the [iterator](#def-b1-linked-structures-iterator) no longer refers to it, and the loop continues with 3 and 4. An [iterator](#def-b1-linked-structures-iterator) is invalidated by any change to the [cells](#def-b1-linked-structures-list) 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.

```c
void free_all(node *head) {
    for (node *p = head; p != NULL; p = p->next) free(p);
}
```

***Listing 15.7.** Freeing a list code/bachelor-1/15-linked-structures/listings/exo_free_bug.c*

**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
```

***Output 15.9.** The sanitizer’s report, shortened. Some lines are left out.*

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](#sec-15-1).

**Exercise 15.6 ★★.**

This [queue](#def-b1-linked-structures-stack) loses its elements after it becomes empty once. Find the case it forgets, state the [representation invariant](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-rep-invariant) it breaks, and repair it.

```c
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;
}
```

***Listing 15.8.** A [queue](#def-b1-linked-structures-stack) code/bachelor-1/15-linked-structures/listings/exo_queue_bug.c*

```
took 1
front is NULL
```

***Output 15.7.** Two elements put, and none at the front. Some lines are left out.*

**Solution of Exercise 15.6.**

`take` does not reset `rear` when the [queue](#def-b1-linked-structures-stack) 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](#def-b1-linked-structures-stack) looks empty while it holds 2 and 3. The repair adds `if (front == NULL) rear = NULL;` after advancing `front`, as in [Listing 15.5](#lst-b1-linked-structures-queue).

**Exercise 15.7 ★★.**

Write `list_reverse(head)`, which reverses a [singly linked list](#def-b1-linked-structures-list) in place in one pass and returns the new first cell. State its [loop invariant](https://one-course.com/books/computer-science/3/en/chapter/12-program-correctness#def-b1-program-correctness-invariant), and test it on lists of length 0, 1 and 6.

**Solution of Exercise 15.7.**

```c
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;
}
```

*Reversal in place code/bachelor-1/15-linked-structures/exercises/reverse.c*

Invariant: `done` is the reversal of the [cells](#def-b1-linked-structures-list) 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, $\Theta(n)$, no allocation. The test reverses a list of six [cells](#def-b1-linked-structures-list), a list of one and the empty list.

**Exercise 15.8 ★★.**

Write a [deque](#def-b1-linked-structures-stack) on a [circular buffer](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-ring) of fixed capacity: push and pop at both ends in $\Theta(1)$. Test it against the [doubly linked list](#def-b1-linked-structures-list).

**Solution of Exercise 15.8.**

```c
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;
}
```

*A [deque](#def-b1-linked-structures-stack) on a ring code/bachelor-1/15-linked-structures/exercises/deque_ring.c*

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](#def-b1-linked-structures-stack) and on the [sentinel](#def-b1-linked-structures-sentinel) list together, against a plain [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) model.

**Exercise 15.9 ★★.**

Prove that $n$ appends at the end of a [singly linked list](#def-b1-linked-structures-list) cost $\Theta(n^2)$ cell visits without a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to the last cell, and $\Theta(n)$ with one.

**Solution of Exercise 15.9.**

Without a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to the last cell, the $j$-th append walks the $j - 1$ [cells](#def-b1-linked-structures-list) already present: $\sum_{j=1}^{n} (j - 1) =
n(n - 1)/2 \in \Theta(n^2)$ visits. With a rear [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer), each append writes the new cell after `rear` and moves `rear`: $\Theta(1)$ each, $\Theta(n)$ in all.

**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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer), one moving one cell at a time and one moving two, and $O(1)$ memory. Test it on lists without a cycle and on every cycle of lists up to length 30.

**Solution of Exercise 15.10.**

```c
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
}
```

*Two [pointers](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) code/bachelor-1/15-linked-structures/exercises/floyd.c*

Without a cycle, `fast` reaches the end and the function returns false. With one, both [pointers](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) 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](#exo-b1-linked-structures-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 $\mu$ [cells](#def-b1-linked-structures-list) before the cycle and a cycle of $\lambda \geq 1$ [cells](#def-b1-linked-structures-list). Prove that the two [pointers](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) of [Exercise 15.10](#exo-b1-linked-structures-10) meet after at most $\mu + \lambda$ steps of the slow [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer).

**Solution of Exercise 15.11.**

Number the [cells](#def-b1-linked-structures-list) $0, 1, \dots$ along the list, the cycle being the [cells](#def-b1-linked-structures-list) $\mu$ to $\mu + \lambda - 1$. After $t$ steps the slow [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) is at cell $t$ and the fast one at cell $2t$ (positions read modulo the cycle once past $\mu$). For $t \geq \mu$ both are in the cycle, and they coincide when $2t \equiv t \pmod \lambda$, that is when $\lambda$ divides $t$. The first meeting is at $t \geq 1$ (at $t = 0$ both are at the start): among the $\lambda$ consecutive integers $\max(\mu, 1), \dots, \max(\mu, 1) + \lambda - 1$ there is a multiple of $\lambda$, so they meet after at most $\mu + \lambda$ steps (exactly $\lambda$ when $\mu = 0$).

**Exercise 15.12 ★★★.**

A [queue](#def-b1-linked-structures-stack) can be made of two [stacks](#def-b1-linked-structures-stack): put pushes on `in`; take pops from `out`, first moving all of `in` onto `out` if `out` is empty. Prove that the [queue](#def-b1-linked-structures-stack) is correct, and that $m$ operations cost $O(m)$ pushes and pops in all.

**Solution of Exercise 15.12.**

Invariant: the [queue](#def-b1-linked-structures-stack), 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](#def-b1-linked-structures-stack) operations per element, so $m$ operations cost at most $4m$, amortised $O(1)$. A single take can cost $\Theta(n)$. 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

$n$ people, numbered 1 to $n$, stand in a circle. Counting starts at person 1, and every $k$-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](#def-b1-linked-structures-list), computes the survivor by a recurrence, and compares both with a closed form for $k = 2$.

```c
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;
}
```

***Listing 15.9.** Simulation, recurrence and closed form code/bachelor-1/15-linked-structures/listings/josephus.c*

```
$ 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
```

***Output 15.8.** The order of departures for $n = 10$, $k = 3$; the three methods for $k = 2$; and the checks.*

**Part I — Simulation.**

1. Follow the simulation for $n = 5$ , $k = 2$ : the departures and the survivor.
2. Why does `simulate` keep a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to the person *before* the next one to count?
3. Why can the [cells](#def-b1-linked-structures-list) live in one [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) , allocated once, although people leave?
4. Show that the simulation costs $\Theta(nk)$ steps.
5. What would the cost be with a [dynamic array](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-dynamic-array) , removing each departing person by shifting the others?
6. Why is the circular list, rather than a list with an end, the natural structure here?

**Part II — The recurrence.**

7. Number the people from 0 to $n - 1$ , and let $J(n, k)$ be the survivor’s number. Show that the first to leave is $(k - 1) \bmod n$ .
8. After that departure, renumber the $n - 1$ remaining people from 0, starting at the person after the one who left. Show that the old number of a person is (new number $+ k) \bmod n$ .
9. Deduce $J(1, k) = 0$ and $J(n, k) = (J(n - 1, k) + k) \bmod n$ .
10. Compute $J(n, 3)$ for $n \leq 10$ and check the survivor of the first line of the output (numbered from 1).
11. What does the recurrence cost, and why is it so much cheaper than the simulation for large $k$ ?
12. Check in the output that the recurrence and the simulation agree for $n \leq 1000$ and $k \leq 7$ .

**Part III — The closed form for $k = 2$.**

13. With people numbered from 1, show that for $n = 2m$ , after the first round the $m$ people left are $1, 3, \dots, 2m - 1$ , and counting starts again at 1; deduce $J(2m) = 2J(m) - 1$ .
14. For $n = 2m + 1$ , the first round removes $2, 4, \dots, 2m$ and then 1; deduce $J(2m + 1) = 2J(m) + 1$ .
15. With $J(1) = 1$ , compute $J(n)$ for $n \leq 16$ and compare with the table.
16. Write $n = 2^a + \ell$ with $0 \leq \ell < 2^a$ . Prove by strong induction that $J(n) = 2\ell + 1$ .
17. What is $J(2^a)$ ? Explain it directly with the rounds.
18. In binary, show that $J(n)$ is $n$ rotated left by one bit (the leading 1 moved to the end).

**Part IV — Checking.**

19. The program checks the closed form against the simulation for $n \leq 10\,000$ . Estimate the number of steps.
20. Why is a simulation a good oracle here, and what does the check add to the proof?
21. An independent test simulates the circle with an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of flags instead of a list. Why test with a second simulation of a different kind?
22. For which $n$ is the survivor person $n$ itself, for $k = 2$ ?
23. For $k = 2$ , how does $J(n + 1)$ compare with $J(n)$ ? Read it on the table.
24. State the named result of the problem, *Josephus for $k = 2$* , with its proof and its check.

**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](#def-b1-linked-structures-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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) is freed at the end.

**4.** Each of the $n - 1$ departures follows $k - 1$ links: $(n - 1)(k - 1)$ steps, in $\Theta(nk)$ for $k \geq 2$.

**5.** Counting is cheap with indices modulo the size, but each removal shifts up to $n$ elements: $\Theta(n^2)$ in the worst case, whatever $k$.

**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 $k$-th person counted is $k - 1$, modulo $n$.

**8.** The new person 0 is the old person $k \bmod n$, the new 1 is old $k + 1$, and so on around the circle.

**9.** With one person, the survivor is 0. Otherwise the survivor of the circle of $n - 1$ is the same person, with new number $J(n - 1, k)$, hence old number $(J(n - 1, k) + k) \bmod n$.

**10.** $J(n, 3)$ for $n = 1, \dots, 10$: 0, 1, 1, 0, 3, 0, 3, 6, 0, 3; from 1, the survivor of ten people is 4, as printed.

**11.** $n - 1$ steps of constant cost, $\Theta(n)$ whatever $k$, against $\Theta(nk)$.

**12.** The last line of the output reports 0 disagreements.

**13.** The first round removes the even numbers $2, 4, \dots, 2m$ and comes back to 1. The person in position $i$ of the new circle is $2i - 1$, so $J(2m) = 2J(m) - 1$.

**14.** After $2, \dots, 2m$, counting goes on with 1, the second counted after $2m$ is 1, which leaves; the circle restarts at 3 with $m$ people $3, 5, \dots, 2m + 1$, position $i$ being $2i + 1$: $J(2m + 1) = 2J(m) + 1$.

**15.** 1, 1, 3, 1, 3, 5, 7, 1, 3, 5, 7, 9, 11, 13, 15, 1, the column of the table.

**16.** $n = 1$: $J = 1$. For $n = 2m$ with $m = 2^{a - 1} + \ell/2$: $J(n) = 2(\ell + 1) - 1 = 2\ell + 1$, using $\ell$ even. For $n = 2m + 1$, $\ell$ is odd and $m = 2^{a - 1} + (\ell - 1)/2$: $J(n) = 2\ell - 1 + 2 = 2\ell + 1$.

**17.** 1: each round halves the circle and restarts at person 1, who is never counted second.

**18.** $n = 1b_{a-1}\dots b_0$ gives $\ell = b_{a-1}\dots b_0$, and $2\ell + 1 = b_{a-1}\dots b_0 1$.

**19.** $\sum_{n \leq 10^4} (n - 1) \approx 5 \times 10^7$ 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](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) simulation are unlikely to be the same.

**22.** $J(n) = n$ when $2\ell + 1 = 2^a + \ell$, that is $\ell = 2^a - 1$: for $n = 2^{a + 1} - 1$, such as 1, 3, 7 and 15.

**23.** $J(n + 1) = J(n) + 2$, except when $n + 1$ is a power of 2, where it falls back to 1.

**24.** *Josephus for $k = 2$*: with $n = 2^a + \ell$, $0 \leq \ell < 2^a$, the survivor is $J(n) = 2\ell + 1 =
2(n - 2^{\lfloor \log_2 n \rfloor}) + 1$, proved from the recurrences of questions 13 and 14 by strong induction, and checked against the simulation for every $n \leq 10\,000$ with no disagreement.
