= Solution
Assume `vector` is a well-formed header satisfying the sparse-vector <representation invariant>; checking that whole invariant on each operation would require traversing the list. Check the requested bounds and value, then find the first stored coordinate at or after the target.
``
def setElement(vector: Node, value: Double, index: Int): Unit = {
require(vector != null)
require(0 <= index && index < vector.index)
require(value != 0.0 && !value.isNaN && !value.isInfinity)
var p = vector.next
while ((p ne vector) && p.index < index) p = p.next
if ((p ne vector) && p.index == index) p.value = value
else {
val fresh = new Node(value, index, p.prev, p)
p.prev.next = fresh
p.prev = fresh
}
}
``
The scan excludes all smaller stored indices. An existing coordinate is updated without duplicating it; otherwise the new node is spliced immediately before `p`, with both directions repaired. The header also serves as the insertion boundary after the final data node. Strict index order and nonzero storage are preserved. The cost is \b[$O(k)$ search and $O(1)$ pointer work], where $k$ is the number of stored entries.
Back to article page