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-2

Exercise 2.2.4-2

not stated yet in Lean solution written

Rating20
KindK8, compute by machine: find a number or an object by a large computation from the written solution
SectionSection 2.2.4 of Volume 1

The task

Draw the before and after pictures of the concatenation of two circular lists by operation (3), when PTR1\mathrm{PTR}_1 and PTR2\mathrm{PTR}_2 are not Λ\Lambda.

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

Operation (3) swaps LINK(PTR1)\mathrm{LINK}(\mathrm{PTR}_1) with LINK(PTR2)\mathrm{LINK}(\mathrm{PTR}_2), and then sets PTR1←PTR2\mathrm{PTR}_1 \leftarrow \mathrm{PTR}_2 and PTR2←Λ\mathrm{PTR}_2 \leftarrow \Lambda.

Solution

Show the solution

Let the first list have nodes a1,…,aka_1, \dots, a_k and the second have nodes b1,…,blb_1, \dots, b_l. The pointer PTR1\mathrm{PTR}_1 points at aka_k, whose link points at a1a_1, and PTR2\mathrm{PTR}_2 points at blb_l, whose link points at b1b_1.

Before:

PTR1 = a_k          PTR2 = b_l
a_1 -> a_2 -> ... -> a_k -> a_1
b_1 -> b_2 -> ... -> b_l -> b_1

After the swap of the two links, aka_k points at b1b_1 and blb_l points at a1a_1. After PTR1←PTR2\mathrm{PTR}_1 \leftarrow \mathrm{PTR}_2 and PTR2←Λ\mathrm{PTR}_2 \leftarrow \Lambda the picture is:

PTR1 = b_l          PTR2 = null
a_1 -> ... -> a_k -> b_1 -> ... -> b_l -> a_1

It is one circle with k+lk + l nodes. The nodes of the first list come first, then the nodes of the second. The pointer PTR1\mathrm{PTR}_1 is at blb_l, which is the rightmost node of the combined list, so the convention that the pointer is at the right end is kept.

Check

For k=3k = 3 and l=2l = 2 the walk from LINK(PTR1)\mathrm{LINK}(\mathrm{PTR}_1) starts at a1a_1, passes a2,a3,b1,b2a_2, a_3, b_1, b_2 and returns to a1a_1, which is five nodes, and PTR1\mathrm{PTR}_1 is b2b_2. A run in python over all 1≤k,l≤61 \le k, l \le 6 confirmed the cycle of length k+lk + l.

Remarks

The operation takes constant time, whatever the lengths of the lists. This is one of the main reasons for using circular lists.

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.