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

Exercise 2.2.5-1

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.2.5 of Volume 1

The task

Give the insertion and the deletion at the left end of a doubly linked list that is represented with the two end pointers LEFT\mathrm{LEFT} and RIGHT\mathrm{RIGHT}.

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 list has nodes with INFO\mathrm{INFO}, LLINK\mathrm{LLINK} and RLINK\mathrm{RLINK}. The end links are Λ\Lambda, and an empty list has LEFT=RIGHT=Λ\mathrm{LEFT} = \mathrm{RIGHT} = \Lambda.

Hint 2

Treat the empty list and the list of one node as special cases.

Solution

Show the solution

Insert YY at the left. Take P⇐AVAILP \Leftarrow \mathrm{AVAIL} and set INFO(P)←Y\mathrm{INFO}(P) \leftarrow Y, LLINK(P)←Λ\mathrm{LLINK}(P) \leftarrow \Lambda, RLINK(P)←LEFT\mathrm{RLINK}(P) \leftarrow \mathrm{LEFT}. If LEFT=Λ\mathrm{LEFT} = \Lambda, the list was empty, so set RIGHT←P\mathrm{RIGHT} \leftarrow P. Otherwise set LLINK(LEFT)←P\mathrm{LLINK}(\mathrm{LEFT}) \leftarrow P. In both cases finish with LEFT←P\mathrm{LEFT} \leftarrow P.

Delete the leftmost node into YY. If LEFT=Λ\mathrm{LEFT} = \Lambda then underflow. Otherwise set P←LEFTP \leftarrow \mathrm{LEFT}, LEFT←RLINK(P)\mathrm{LEFT} \leftarrow \mathrm{RLINK}(P), and then: if LEFT=Λ\mathrm{LEFT} = \Lambda the list is now empty, so set RIGHT←Λ\mathrm{RIGHT} \leftarrow \Lambda; otherwise set LLINK(LEFT)←Λ\mathrm{LLINK}(\mathrm{LEFT}) \leftarrow \Lambda. Finally Y←INFO(P)Y \leftarrow \mathrm{INFO}(P) and AVAIL⇐P\mathrm{AVAIL} \Leftarrow P.

The two operations at the right end are the same with LEFT\mathrm{LEFT} and RIGHT\mathrm{RIGHT} exchanged and LLINK\mathrm{LLINK} and RLINK\mathrm{RLINK} exchanged. The four operations together make a general deque.

Check

Insert 1,2,31, 2, 3 at the left. The list is 3,2,13, 2, 1 with LEFT\mathrm{LEFT} at 33 and RIGHT\mathrm{RIGHT} at 11. Three deletions at the left give 3,2,13, 2, 1 in this order, and after the last one LEFT=RIGHT=Λ\mathrm{LEFT} = \mathrm{RIGHT} = \Lambda. A mixed sequence of insertions and deletions at both ends was compared with a python deque in 1000 random runs, with equal results.

Remarks

Each end is handled by its own pair of links, so no operation has to walk along the list.

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.