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.1-4

Exercise 2.1-4

not stated yet in Lean solution written

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

The task

Write an algorithm that puts the new card, face down, at the bottom of the pile. The pile may be empty.

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

The bottom card is the one whose NEXT field is Λ\Lambda. You must walk down the pile to find it.

Hint 2

An empty pile needs a special case, because then the link to change is TOP, not a NEXT field. Find a way to treat both with the same step.

Solution

Show the solution

Plan. Walk down the pile with a link variable X to the last node. Then put the new card after it. To avoid a special case, let X start at the address of the variable TOP, and assume that the value of TOP is stored in the NEXT field of the word that holds it. The program (5) of the section has this property. Then TOP == NEXT(LOC(TOP)), and the variable TOP plays the role of a card whose link is the first card.

D1. Set X ←\gets LOC(TOP).

D2. If NEXT(X) ≠Λ\ne \Lambda, set X ←\gets NEXT(X) and repeat this step.

D3. Set NEXT(X) ←\gets NEWCARD, NEXT(NEWCARD) ←Λ\gets \Lambda and TAG(NEWCARD) ←1\gets 1.

After D2, X points to the last card, or to LOC(TOP) if the pile is empty. In both cases NEXT(X) is Λ\Lambda at this point. Step D3 links the new card there. If the pile was empty, D3 sets TOP == NEWCARD. The new card gets the null link, because it is now the last card, and the tag 11 means that it is face down.

The loop takes as many steps as there are cards. This is the price of a pile that has only a TOP pointer.

Check

Use the pile of (3) and a new card at address 500500. D1 sets X =LOC(TOP)= \mathrm{LOC(TOP)}, whose NEXT field holds 242242. D2 moves X to 242242, then to 386386, then to 100100. Here NEXT(100) =Λ= \Lambda, so the loop stops. D3 sets NEXT(100) ←500\gets 500, NEXT(500) ←Λ\gets \Lambda and TAG(500) ←1\gets 1. The pile has four cards, and the last one is face down. For an empty pile D2 does not repeat, and D3 gives TOP =500= 500.

Remarks

If the pile must grow often at the bottom, the walk is too slow. A second variable that points to the bottom card, as in the queues of Section 2.2.1, removes the walk. Exercise 2.1-5 asks for the reverse operation.

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.