Exercise · Volume 1 · 2.1-3
Exercise 2.1-3
not stated yet in Lean solution written
| Rating | 11 |
|---|---|
| Kind | K5, design an algorithm: give a method for a task, often with a cost bound from the written solution |
| Section | Section 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 , because then there is no card to remove.
Solution
Show the solution
The algorithm has two steps.
C1. Set NEWCARD TOP.
C2. If TOP , set TOP 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 . C2 does nothing. So NEWCARD tells the caller that no card was removed.
Check
Use the pile of (3), with TOP . C1 sets NEWCARD . C2 sets TOP . Now the pile has two cards. Run algorithm A with NEWCARD : it sets NEXT(242) , TOP , and TAG(242) . 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.