Sub topic 4
Searching from the top layer down
This chapter assumes you know singly linked list traversal, Big-O notation, and basic Python. It also assumes you have seen the node layout from the previous chapter. Each node has a key and a forward list. The head sentinel is a node with no key and one pointer per layer.
The idea
A skip list search starts at the head, on the highest layer in use. At each layer, you move right while the next key is smaller than the target. When the next key is the target or larger, or there is no next node, you drop one layer down at the same node. You repeat this until you finish layer 0.
At that point the current node is the last node whose key is less than the target. Its layer-0 successor is the only node that can match.
A traceable example
The code below builds a small list by hand with fixed heights, so the path is predictable. It then searches while printing every step. Each pair is (key, height). Layer indexes start at 0, so a node of height 3 appears on layers 0, 1 and 2.
class Node:
__slots__ = ("key", "forward")
def __init__(self, key, level):
self.key = key
self.forward = [None] * level
MAX_LEVEL = 4
def build(pairs):
head = Node(None, MAX_LEVEL)
tails = [head] * MAX_LEVEL
for key, height in pairs:
node = Node(key, height)
for i in range(height):
tails[i].forward[i] = node
tails[i] = node
return head
def search(head, key, top):
node = head
for i in range(top - 1, -1, -1):
while node.forward[i] is not None and node.forward[i].key < key:
node = node.forward[i]
print(f"layer {i}: move to {node.key}")
label = "head" if node.key is None else node.key
print(f"layer {i}: drop down at {label}")
candidate = node.forward[0]
return candidate is not None and candidate.key == key
head = build([(1, 1), (3, 2), (4, 1), (6, 3), (9, 1), (12, 2)])
print("found 12:", search(head, 12, 3))
print("found 5:", search(head, 5, 3))Output:
layer 2: move to 6
layer 2: drop down at 6
layer 1: drop down at 6
layer 0: move to 9
layer 0: drop down at 9
found 12: True
layer 2: drop down at head
layer 1: move to 3
layer 1: drop down at 3
layer 0: move to 4
layer 0: drop down at 4
found 5: FalseSearching for 12 takes one long jump on layer 2 to key 6. Layer 1 offers nothing useful, because its next key is 12, which is not less than 12. Layer 0 then takes one short step to 9. A plain linked list would have taken six steps.
How this appears in the full class
The SkipList class in this tutorial wraps the same loop in _find_predecessors. That method starts at self.level - 1, the highest layer actually in use, instead of MAX_LEVEL - 1. This skips empty layers. It also records the node where each layer ended, in an update array.
def _find_predecessors(self, key):
update = [self.head] * self.MAX_LEVEL
node = self.head
for i in range(self.level - 1, -1, -1):
while node.forward[i] is not None and node.forward[i].key < key:
node = node.forward[i]
update[i] = node
return update
def contains(self, key):
node = self._find_predecessors(key)[0].forward[0]
return node is not None and node.key == keycontains only needs update[0]. Insert and delete use the whole array, which is why one routine serves all three operations.
Common errors
- Using
<=instead of<. The loop would move onto the target and stop at the node itself. You would then have no predecessor to splice around, and you would have to checknode.keydirectly. - Checking only the current layer for a match. A key may appear on several layers. The reliable check is the layer-0 successor after the descent.
- Starting at
MAX_LEVELwithout handlingNone. Upper layers at the head are usually empty. Theis not Nonetest makes the loop fall through to the next layer, but it wastes work, so trackself.level. - Forgetting that the head has no key. Never compare
head.key. The loop avoids this because it only comparesnode.forward[i].key.
Exercise
Using the list built above, trace search(head, 4, 3). Which lines would it print, and what does it return?
Show answer
Layer 2: the head's next key is 6, which is not less than 4, so it prints "layer 2: drop down at head". Layer 1: the next key is 3, so it prints "layer 1: move to 3", and then 6 stops it, so "layer 1: drop down at 3". Layer 0: the next key is 4, which is not less than 4, so it prints "layer 0: drop down at 3". The layer-0 successor of node 3 is 4, so it returns True.