Exercise · Volume 1 · 2.2.5-1
Exercise 2.2.5-1
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.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 and .
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 , and . The end links are , and an empty list has .
Hint 2
Treat the empty list and the list of one node as special cases.
Solution
Show the solution
Insert at the left. Take and set , , . If , the list was empty, so set . Otherwise set . In both cases finish with .
Delete the leftmost node into . If then underflow. Otherwise set , , and then: if the list is now empty, so set ; otherwise set . Finally and .
The two operations at the right end are the same with and exchanged and and exchanged. The four operations together make a general deque.
Check
Insert at the left. The list is with at and at . Three deletions at the left give in this order, and after the last one . 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.