taocp

This site has no text of the book. Keep your own copy of TAOCP next to it. See what is checked.

Exercise · Volume 1 · 2.2.4-5

Exercise 2.2.4-5

not stated yet in Lean solution written

Rating21
KindK5, design an algorithm: give a method for a task, often with a cost bound from the written solution
SectionSection 2.2.4 of Volume 1

The task

Design an algorithm that reverses the direction of all the links of a circular list such as the one of the text.

The exact wording is in your copy of the book.

Hints

Open one hint at a time. Try the exercise again after each.

Hint 1

Walk around the circle with three pointers: the previous node, the current node and the next node. The next node must be saved before the link of the current node is changed.

Hint 2

Do not forget the node where you started.

Solution

Show the solution

Let PTR\mathrm{PTR} point at the last node xnx_n of the list x1,…,xnx_1, \dots, x_n, so that LINK(xn)=x1\mathrm{LINK}(x_n) = x_1. If PTR=Λ\mathrm{PTR} = \Lambda there is nothing to do.

R1. Set R←PTRR \leftarrow \mathrm{PTR} and Q←LINK(R)Q \leftarrow \mathrm{LINK}(R).

R2. Set S←LINK(Q)S \leftarrow \mathrm{LINK}(Q), LINK(Q)←R\mathrm{LINK}(Q) \leftarrow R, R←QR \leftarrow Q, Q←SQ \leftarrow S.

R3. If R≠PTRR \ne \mathrm{PTR} go back to R2. Otherwise set PTR←Q\mathrm{PTR} \leftarrow Q and stop.

At the first execution of R2 the node x1x_1 gets the link to xnx_n. After the step for xkx_k the link of xkx_k is xk−1x_{k-1}, and the pointer RR is xkx_k. The step for xnx_n is the last one, since then R=PTRR = \mathrm{PTR}. At that moment Q=S=x1Q = S = x_1, because SS was the old link of xnx_n. Now xnx_n points at xn−1x_{n-1} and x1x_1 points at xnx_n. In the reversed list the last node is x1x_1, which is QQ, so PTR←Q\mathrm{PTR} \leftarrow Q keeps the convention that PTR\mathrm{PTR} points at the last node.

The algorithm uses nn passes through R2 and a constant number of variables.

Check

For n=1n = 1 the single pass sets LINK(x1)←x1\mathrm{LINK}(x_1) \leftarrow x_1, and the list is unchanged. For n=2n = 2, x1→x2→x1x_1 \to x_2 \to x_1 becomes x2→x1→x2x_2 \to x_1 \to x_2 with PTR=x1\mathrm{PTR} = x_1. A python run over 1≤n≤71 \le n \le 7 gave the reversed order xn,…,x1x_n, \dots, x_1 and PTR=x1\mathrm{PTR} = x_1 each time.

Remarks

This is the circular version of the reversal of a linear list in the previous section. The only change is the stop test, which compares with PTR\mathrm{PTR} instead of Λ\Lambda.

This solution is drafted, and a person has not reviewed it yet. The source.

In Lean

not stated yet The exercise is not stated in Lean yet.

The status is computed from the Lean build. The node of the map.

Something is wrong? Report it.