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.2.4-4

Exercise 2.2.4-4

not stated yet in Lean solution written

Rating20
KindK5, design an algorithm: give a method for a task, often with a cost bound from the written solution
SectionSection 2.2.4 of Volume 1

The task

With representation (4), where the list has a list head, give the insertion and deletion that make the list work as a stack.

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 place where a stack changes is next to the list head.

Solution

Show the solution

Let HEAD\mathrm{HEAD} be the address of the list head. The stack is the circle HEAD,x1,…,xn\mathrm{HEAD}, x_1, \dots, x_n where x1x_1 is the top. It is empty when LINK(HEAD)=HEAD\mathrm{LINK}(\mathrm{HEAD}) = \mathrm{HEAD}.

To push the item YY: take P⇐AVAILP \Leftarrow \mathrm{AVAIL}, set INFO(P)←Y\mathrm{INFO}(P) \leftarrow Y, then LINK(P)←LINK(HEAD)\mathrm{LINK}(P) \leftarrow \mathrm{LINK}(\mathrm{HEAD}) and LINK(HEAD)←P\mathrm{LINK}(\mathrm{HEAD}) \leftarrow P.

To pop into YY: if LINK(HEAD)=HEAD\mathrm{LINK}(\mathrm{HEAD}) = \mathrm{HEAD}, the stack is empty and we have underflow. Otherwise P←LINK(HEAD)P \leftarrow \mathrm{LINK}(\mathrm{HEAD}), LINK(HEAD)←LINK(P)\mathrm{LINK}(\mathrm{HEAD}) \leftarrow \mathrm{LINK}(P), Y←INFO(P)Y \leftarrow \mathrm{INFO}(P) and AVAIL⇐P\mathrm{AVAIL} \Leftarrow P.

No special case for the empty list is needed in the push, and none in the pop apart from the underflow test, which is the reason for the list head.

Check

Push 1,2,31, 2, 3 and pop three times. The items come out in the order 3,2,13, 2, 1. After the last pop LINK(HEAD)=HEAD\mathrm{LINK}(\mathrm{HEAD}) = \mathrm{HEAD} again.

Remarks

The same two operations at the other end need a pointer to the last node, which is why the text keeps PTR\mathrm{PTR} at the right end for queues.

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.