Introduction
Searching quickly through a long list of items can be slow if you check each item one by one. Skip lists solve this by adding shortcuts that let you jump ahead, making searches faster without complex balancing.
Imagine walking through a long hallway with many doors. Instead of checking every door, you use a set of balconies above that let you jump ahead several doors at once. Sometimes you drop down to the hallway to check doors closely, but mostly you use the balconies to move quickly.
┌───────────────┐ │ Level 3 (top) │ → → → → → ├───────────────┤ │ Level 2 │ → → → → → ├───────────────┤ │ Level 1 │ → → → → → ├───────────────┤ │ Level 0 (base)│ → → → → → Arrows show forward pointers; higher levels skip more elements.
import random class Node: def __init__(self, value, level): self.value = value self.forward = [None] * (level + 1) class SkipList: MAX_LEVEL = 4 P = 0.5 def __init__(self): self.header = Node(None, self.MAX_LEVEL) self.level = 0 def random_level(self): lvl = 0 while random.random() < self.P and lvl < self.MAX_LEVEL: lvl += 1 return lvl def insert(self, value): update = [None] * (self.MAX_LEVEL + 1) current = self.header for i in reversed(range(self.level + 1)): while current.forward[i] and current.forward[i].value < value: current = current.forward[i] update[i] = current current = current.forward[0] if current is None or current.value != value: lvl = self.random_level() if lvl > self.level: for i in range(self.level + 1, lvl + 1): update[i] = self.header self.level = lvl new_node = Node(value, lvl) for i in range(lvl + 1): new_node.forward[i] = update[i].forward[i] update[i].forward[i] = new_node def search(self, value): current = self.header for i in reversed(range(self.level + 1)): while current.forward[i] and current.forward[i].value < value: current = current.forward[i] current = current.forward[0] if current and current.value == value: return True return False # Example usage skiplist = SkipList() skiplist.insert(3) skiplist.insert(6) skiplist.insert(7) skiplist.insert(9) skiplist.insert(12) skiplist.insert(19) skiplist.insert(17) skiplist.insert(26) skiplist.insert(21) skiplist.insert(25) print(skiplist.search(19)) print(skiplist.search(15))