计算机科学 · 第 3 册 · 本科一年级

University Computer Science — Year 1

本书暂未推出简体中文版。现有版本: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 ii-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;
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: Θ(1)\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.
A singly linked list 1,2,31, 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 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;
}
Listing 15.2. Removal through a 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.
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.

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;
}
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,41, 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 ii-th element, finding a value, and appending at the end without a pointer to the last cell all walk the list: Θ(n)\Theta(n). 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 Θ(1)\Theta(1) 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);
}
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 with a sentinel, every cell, the sentinel included, has a predecessor and a successor, and c->next->prev=c=c->prev->nextc\text{->next->prev} = c = c\text{->prev->next} for every cell cc. 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 nn after cc, with d=c->nextd = c\text{->next}: afterwards c→n→dc \to n \to d and d→n→cd \to n \to c backwards, every other link unchanged, so the property holds at cc, nn and dd, and elsewhere as before. Removal of cc between pp and dd links pp and dd to each other both ways, which restores the property at both. No step uses a null pointer, 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.
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.
$ 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 implementation and a linked one. A stack on a dynamic array pushes and pops at the end, in amortised Θ(1)\Theta(1); on a singly linked list, at the front, in Θ(1)\Theta(1). 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;
}
Listing 15.5. A queue on a linked list with a 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.
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.

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
Output 15.4. The bracket checker linked with the array stack and with the linked stack.

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;
}
Listing 15.6. One iterator type for lists and arrays, 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 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

operationdynamic arraysingly linked listdoubly linked list
access the ii-th elementΘ(1)\Theta(1)Θ(i)\Theta(i)Θ(i)\Theta(i)
add or remove at the frontΘ(n)\Theta(n)Θ(1)\Theta(1)Θ(1)\Theta(1)
add or remove at the endamortised Θ(1)\Theta(1)Θ(1)\Theta(1) to add (rear pointer)Θ(1)\Theta(1)
insert after a known positionΘ(n)\Theta(n)Θ(1)\Theta(1)Θ(1)\Theta(1)
remove a known cellΘ(n)\Theta(n)Θ(n)\Theta(n) (find the one before)Θ(1)\Theta(1)
memory per element1 to 4 cellselement + 1 pointerelement + 2 pointers

The table counts operations. A traversal of nn elements is Θ(n)\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 2222^{22} integers on the author’s laptop: in an array, in a list whose cells follow each other in memory, and in the same list after shuffling the order of its cells.

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.

33; 8,38, 3; 1,8,31, 8, 3; 1,5,8,31, 5, 8, 3; 1,5,31, 5, 3; 2,1,5,32, 1, 5, 3; and finally 1,5,31, 5, 3.

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?

Solution

Solution of Exercise 15.2.

The stack returns 3, 4 and 2, and holds 1. The queue returns 1, 2 and 3, and holds 4.

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.

Solution

Solution of Exercise 15.3.

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

Exercise 15.4 ★

An iterator over the list 1,2,3,41, 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

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);
}
Listing 15.7. Freeing a list code/bachelor-1/15-linked-structures/listings/exo_free_bug.c
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
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.

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;
}
Listing 15.8. A queue 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

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;
}
Reversal in place code/bachelor-1/15-linked-structures/exercises/reverse.c

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, Θ(n)\Theta(n), 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 Θ(1)\Theta(1). 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;
}
A deque 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 and on the sentinel list together, against a plain array model.

Exercise 15.9 ★★

Prove that nn appends at the end of a singly linked list cost Θ(n2)\Theta(n^2) cell visits without a pointer to the last cell, and Θ(n)\Theta(n) with one.

Solution

Solution of Exercise 15.9.

Without a pointer to the last cell, the jj-th append walks the j−1j - 1 cells already present: ∑j=1n(j−1)=n(n−1)/2∈Θ(n2)\sum_{j=1}^{n} (j - 1) = n(n - 1)/2 \in \Theta(n^2) visits. With a rear pointer, each append writes the new cell after rear and moves rear: Θ(1)\Theta(1) each, Θ(n)\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, one moving one cell at a time and one moving two, and O(1)O(1) 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
}
Two pointers 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 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 μ\mu cells before the cycle and a cycle of λ≥1\lambda \geq 1 cells. Prove that the two pointers of Exercise 15.10 meet after at most μ+λ\mu + \lambda steps of the slow pointer.

Solution

Solution of Exercise 15.11.

Number the cells 0,1,…0, 1, \dots along the list, the cycle being the cells μ\mu to μ+λ−1\mu + \lambda - 1. After tt steps the slow pointer is at cell tt and the fast one at cell 2t2t (positions read modulo the cycle once past μ\mu). For t≥μt \geq \mu both are in the cycle, and they coincide when 2t≡t(modλ)2t \equiv t \pmod \lambda, that is when λ\lambda divides tt. The first meeting is at t≥1t \geq 1 (at t=0t = 0 both are at the start): among the λ\lambda consecutive integers max⁡(μ,1),…,max⁡(μ,1)+λ−1\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 μ=0\mu = 0).

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 mm operations cost O(m)O(m) 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 mm operations cost at most 4m4m, amortised O(1)O(1). A single take can cost Θ(n)\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

nn people, numbered 1 to nn, stand in a circle. Counting starts at person 1, and every kk-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 k=2k = 2.

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=10n = 10, k=3k = 3; the three methods for k=2k = 2; and the checks.

Part I — Simulation.

  1. Follow the simulation for n=5n = 5, k=2k = 2: the departures and the survivor.
  2. Why does simulate keep a pointer to the person before the next one to count?
  3. Why can the cells live in one array, allocated once, although people leave?
  4. Show that the simulation costs Θ(nk)\Theta(nk) steps.
  5. What would the cost be with a 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.

  1. Number the people from 0 to n−1n - 1, and let J(n,k)J(n, k) be the survivor’s number. Show that the first to leave is (k−1) mod n(k - 1) \bmod n.
  2. After that departure, renumber the n−1n - 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) mod n+ k) \bmod n.
  3. Deduce J(1,k)=0J(1, k) = 0 and J(n,k)=(J(n−1,k)+k) mod nJ(n, k) = (J(n - 1, k) + k) \bmod n.
  4. Compute J(n,3)J(n, 3) for n≤10n \leq 10 and check the survivor of the first line of the output (numbered from 1).
  5. What does the recurrence cost, and why is it so much cheaper than the simulation for large kk?
  6. Check in the output that the recurrence and the simulation agree for n≤1000n \leq 1000 and k≤7k \leq 7.

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

  1. With people numbered from 1, show that for n=2mn = 2m, after the first round the mm people left are 1,3,…,2m−11, 3, \dots, 2m - 1, and counting starts again at 1; deduce J(2m)=2J(m)−1J(2m) = 2J(m) - 1.
  2. For n=2m+1n = 2m + 1, the first round removes 2,4,…,2m2, 4, \dots, 2m and then 1; deduce J(2m+1)=2J(m)+1J(2m + 1) = 2J(m) + 1.
  3. With J(1)=1J(1) = 1, compute J(n)J(n) for n≤16n \leq 16 and compare with the table.
  4. Write n=2a+ℓn = 2^a + \ell with 0≤ℓ<2a0 \leq \ell < 2^a. Prove by strong induction that J(n)=2ℓ+1J(n) = 2\ell + 1.
  5. What is J(2a)J(2^a)? Explain it directly with the rounds.
  6. In binary, show that J(n)J(n) is nn rotated left by one bit (the leading 1 moved to the end).

Part IV — Checking.

  1. The program checks the closed form against the simulation for n≤10 000n \leq 10\,000. Estimate the number of steps.
  2. Why is a simulation a good oracle here, and what does the check add to the proof?
  3. 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?
  4. For which nn is the survivor person nn itself, for k=2k = 2?
  5. For k=2k = 2, how does J(n+1)J(n + 1) compare with J(n)J(n)? Read it on the table.
  6. State the named result of the problem, Josephus for k=2k = 2, 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 n−1n - 1 departures follows k−1k - 1 links: (n−1)(k−1)(n - 1)(k - 1) steps, in Θ(nk)\Theta(nk) for k≥2k \geq 2.

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

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 kk-th person counted is k−1k - 1, modulo nn.

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

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

10. J(n,3)J(n, 3) for n=1,…,10n = 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−1n - 1 steps of constant cost, Θ(n)\Theta(n) whatever kk, against Θ(nk)\Theta(nk).

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

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

14. After 2,…,2m2, \dots, 2m, counting goes on with 1, the second counted after 2m2m is 1, which leaves; the circle restarts at 3 with mm people 3,5,…,2m+13, 5, \dots, 2m + 1, position ii being 2i+12i + 1: J(2m+1)=2J(m)+1J(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=1n = 1: J=1J = 1. For n=2mn = 2m with m=2a−1+ℓ/2m = 2^{a - 1} + \ell/2: J(n)=2(ℓ+1)−1=2ℓ+1J(n) = 2(\ell + 1) - 1 = 2\ell + 1, using ℓ\ell even. For n=2m+1n = 2m + 1, ℓ\ell is odd and m=2a−1+(ℓ−1)/2m = 2^{a - 1} + (\ell - 1)/2: J(n)=2ℓ−1+2=2ℓ+1J(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=1ba−1…b0n = 1b_{a-1}\dots b_0 gives ℓ=ba−1…b0\ell = b_{a-1}\dots b_0, and 2ℓ+1=ba−1…b012\ell + 1 = b_{a-1}\dots b_0 1.

19. ∑n≤104(n−1)≈5×107\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 simulation are unlikely to be the same.

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

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

24. Josephus for k=2k = 2: with n=2a+ℓn = 2^a + \ell, 0≤ℓ<2a0 \leq \ell < 2^a, the survivor is J(n)=2ℓ+1=2(n−2⌊log⁡2n⌋)+1J(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≤10 000n \leq 10\,000 with no disagreement.

本章定义的术语

在术语表中查看全部 1050 个术语