Exercise · Volume 1 · 2.1-4
Exercise 2.1-4
not stated yet in Lean solution written
| Rating | 18 |
|---|---|
| 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 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 . 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 LOC(TOP).
D2. If NEXT(X) , set X NEXT(X) and repeat this step.
D3. Set NEXT(X) NEWCARD, NEXT(NEWCARD) and TAG(NEWCARD) .
After D2, X points to the last card, or to LOC(TOP) if the pile is empty. In both cases NEXT(X) is 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 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 . D1 sets X , whose NEXT field holds . D2 moves X to , then to , then to . Here NEXT(100) , so the loop stops. D3 sets NEXT(100) , NEXT(500) and TAG(500) . The pile has four cards, and the last one is face down. For an empty pile D2 does not repeat, and D3 gives TOP .
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.