Exercise · Volume 1 · 2.2.4-18
Exercise 2.2.4-18
not stated yet in Lean solution written
| Rating | 25 |
|---|---|
| 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 a way of representing a circular list that can be walked in both directions, with only one link field in each node. The hint says that two pointers to successive nodes and should be enough to find 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
Put into the link of a node a value from which, given one of its two neighbours, one gets the other.
Hint 2
The exclusive or of two bit strings is its own inverse.
Solution
Show the solution
Let denote the address of a node, and let be the exclusive or of the bits of two addresses. In the node store
Suppose we know and . Then
because . This gives the forward walk: from the pair we get the pair . The backward walk is symmetric. From the same pair,
and the pair gives . So the direction is decided only by the order in which we keep the two pointers.
An operation needs a start, that is, two adjacent nodes. It is convenient to keep two adjacent nodes in the circle as list heads, which are never deleted. Their addresses are known, so one can always start from them, and a list with no items is a circle of those two nodes.
To insert a new node between adjacent nodes and , set , and . The deletion of between and is the same two updates of and , because undoes itself, and then is freed.
Any operation that can be undone can replace . Addition modulo the size of the address space works too: store , and recover by subtracting .
Check
With 8 random addresses in a circle, the forward walk from two adjacent nodes returned the original order, the backward walk returned the reversed order, and a node inserted between two adjacent nodes appeared in the walk, and disappeared again after the deletion.
Remarks
The cost is that a walk always needs two pointers, and one cannot jump to a node by its address and then move, since the neighbour is unknown. The storage is the same as for a singly linked 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.