Exercise · Volume 1 · 2.2.4-5
Exercise 2.2.4-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.2.4 of Volume 1 |
The task
Design an algorithm that reverses the direction of all the links of a circular list such as the one of the text.
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
Walk around the circle with three pointers: the previous node, the current node and the next node. The next node must be saved before the link of the current node is changed.
Hint 2
Do not forget the node where you started.
Solution
Show the solution
Let point at the last node of the list , so that . If there is nothing to do.
R1. Set and .
R2. Set , , , .
R3. If go back to R2. Otherwise set and stop.
At the first execution of R2 the node gets the link to . After the step for the link of is , and the pointer is . The step for is the last one, since then . At that moment , because was the old link of . Now points at and points at . In the reversed list the last node is , which is , so keeps the convention that points at the last node.
The algorithm uses passes through R2 and a constant number of variables.
Check
For the single pass sets , and the list is unchanged. For , becomes with . A python run over gave the reversed order and each time.
Remarks
This is the circular version of the reversal of a linear list in the previous section. The only change is the stop test, which compares with instead of .
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.