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

Exercise 2.1-3

not stated yet in Lean solution written

Rating11
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 takes the top card off the pile and puts its address in NEWCARD. It must also handle an empty pile.

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

Algorithm A has three steps. Reverse them in order and in meaning.

Hint 2

Decide what to do when TOP is Λ\Lambda, because then there is no card to remove.

Solution

Show the solution

The algorithm has two steps.

C1. Set NEWCARD ←\gets TOP.

C2. If TOP ≠Λ\ne \Lambda, set TOP ←\gets NEXT(TOP).

If the pile has cards, C1 saves the address of the top card, and C2 makes the second card the new top. The old top card is now a separate node, and NEWCARD points to it. Its NEXT field still holds the old link. This does no harm, because algorithm A sets this field again when the card is put back.

If the pile is empty, C1 sets NEWCARD =Λ= \Lambda. C2 does nothing. So NEWCARD =Λ= \Lambda tells the caller that no card was removed.

Check

Use the pile of (3), with TOP =242= 242. C1 sets NEWCARD =242= 242. C2 sets TOP =386= 386. Now the pile has two cards. Run algorithm A with NEWCARD =242= 242: it sets NEXT(242) ←386\gets 386, TOP ←242\gets 242, and TAG(242) ←0\gets 0. This restores the pile.

Remarks

The pair of algorithms is the push and the pop of a stack of Section 2.2.1. The algorithm does not change the tag of the removed card. If the caller needs a face-up card, it must set the tag itself.

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.