Exercise · Volume 1 · 2.1-5
Exercise 2.1-5
not stated yet in Lean solution written
| Rating | 21 |
|---|---|
| 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 removes the bottom card of a non-empty pile and makes NEWCARD point to it. It undoes Exercise 2.1-4.
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
To cut the last card off, you need the address of the card before it. Keep two link variables, one step apart.
Hint 2
Treat the one-card pile with the same step as the others, by letting the trailing variable start at LOC(TOP).
Solution
Show the solution
Plan. Use two links X and Y with Y NEXT(X) at all times. Move them down until Y is the bottom card. Then cut it off. As in Exercise 2.1-4, assume that TOP is stored as the NEXT field of the word at LOC(TOP).
E1. Set X LOC(TOP) and Y TOP. (By assumption, .)
E2. If NEXT(Y) , set X Y, Y NEXT(Y), and repeat this step.
E3. (Now Y is the bottom card and X is the card above it.) Set NEXT(X) and NEWCARD Y.
Step E2 keeps Y NEXT(X). It stops when NEXT(Y) , so Y is the bottom card. E3 cuts the link from X to Y, so the pile ends at X. If the pile had one card, X is still LOC(TOP), and E3 sets TOP , which gives the empty pile.
Check
Use the pile of (3). E1 gives X and Y . E2 moves the pair to , then to , and stops because NEXT(100) . E3 sets NEXT(386) and NEWCARD . The pile now has the cards at and . Now apply Exercise 2.1-4 with this NEWCARD: the card at goes back to the bottom, face down, and the pile is as in (3) except for the tag of the bottom card.
Remarks
The tag of the removed card is not changed. If the bottom card was put there by Exercise 2.1-4, its tag is . The need for a trailing pointer is the main weakness of a singly linked list. Doubly linked lists (Section 2.2.5) remove it.
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.