A Sentinel Node at a List Boundary

A sentinel node represents a structural boundary, so ordinary nodes can use a more uniform neighbor rule at the ends.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace an insertion at the front
  2. Keep the dummy out of data
  3. Apply the same link changes at the boundary
  4. Write tests that detect sentinel leakage

Trace an insertion at the front

With a dummy head pointing to A, inserting B at the front updates the dummy's next to B and B's next to A. A later insertion after a real node uses the same pair of link edits. This extends linked list mechanics.

Keep the dummy out of data

An empty list may have its head sentinel pointing to no ordinary node. Stop traversal according to that representation and protect the sentinel from removal. Sentinel values illustrate why boundary markers need a distinct identity.[1]

Apply the same link changes at the boundary

In a circular doubly linked list with sentinel S, an empty list has both of S's links pointing to itself. To insert A, link A to S in both directions, then link S to A in both directions. The sentinel is infrastructure rather than a value. See doubly linked lists.

Empty: S.next=S, S.prev=S
Add A: S.next=A, S.prev=A, A.next=S, A.prev=S
Remove A: S.next=S, S.prev=S
Iteration stops at S on all three states

Write tests that detect sentinel leakage

Iterating an empty list should produce zero elements. With one value the traversal should stop after it, even if it compares equal to a default data value. Detect the sentinel by identity or an explicit role rather than value equality.

References

  1. Jeff Erickson, Algorithms ↩