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

Exercise 2.1-5

not stated yet in Lean solution written

Rating21
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 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 ←\gets LOC(TOP) and Y ←\gets TOP. (By assumption, Y≠ΛY \ne \Lambda.)

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

E3. (Now Y is the bottom card and X is the card above it.) Set NEXT(X) ←Λ\gets \Lambda and NEWCARD ←\gets Y.

Step E2 keeps Y == NEXT(X). It stops when NEXT(Y) =Λ= \Lambda, 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 =Λ= \Lambda, which gives the empty pile.

Check

Use the pile of (3). E1 gives X =LOC(TOP)= \mathrm{LOC(TOP)} and Y =242= 242. E2 moves the pair to (242,386)(242, 386), then to (386,100)(386, 100), and stops because NEXT(100) =Λ= \Lambda. E3 sets NEXT(386) ←Λ\gets \Lambda and NEWCARD =100= 100. The pile now has the cards at 242242 and 386386. Now apply Exercise 2.1-4 with this NEWCARD: the card at 100100 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 11. 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.