|
| 1 | +import random |
| 2 | + |
| 3 | + |
| 4 | +class Node: |
| 5 | + def __init__(self, height, value): |
| 6 | + self.value = value |
| 7 | + self.forward = [None] * height |
| 8 | + |
| 9 | + |
| 10 | +class SkipList: |
| 11 | + MAX_HEIGHT = 16 |
| 12 | + P = 0.5 |
| 13 | + |
| 14 | + def __init__(self): |
| 15 | + self.head = Node(self.MAX_HEIGHT, None) |
| 16 | + self.level = 1 |
| 17 | + self.length = 0 |
| 18 | + |
| 19 | + def __len__(self): |
| 20 | + return self.length |
| 21 | + |
| 22 | + def random_height(self): |
| 23 | + height = 1 |
| 24 | + while random.random() < self.P and height < self.MAX_HEIGHT: |
| 25 | + height += 1 |
| 26 | + return height |
| 27 | + |
| 28 | + def _find_updated_path(self, value): |
| 29 | + update = [None] * self.MAX_HEIGHT |
| 30 | + current = self.head |
| 31 | + for i in range(self.level - 1, -1, -1): |
| 32 | + while current.forward[i] and current.forward[i].value < value: |
| 33 | + current = current.forward[i] |
| 34 | + update[i] = current |
| 35 | + return update |
| 36 | + |
| 37 | + def __contains__(self, value): |
| 38 | + current = self.head |
| 39 | + |
| 40 | + for i in range(self.level - 1, -1, -1): |
| 41 | + while current.forward[i] and current.forward[i].value < value: |
| 42 | + current = current.forward[i] |
| 43 | + |
| 44 | + current = current.forward[0] |
| 45 | + return current is not None and current.value == value |
| 46 | + |
| 47 | + def insert(self, value): |
| 48 | + update = self._find_updated_path(value) |
| 49 | + forward_node = update[0].forward[0] |
| 50 | + |
| 51 | + if forward_node and forward_node.value == value: |
| 52 | + return |
| 53 | + node_height = self.random_height() |
| 54 | + if node_height > self.level: |
| 55 | + for i in range(self.level, node_height): |
| 56 | + update[i] = self.head |
| 57 | + self.level = node_height |
| 58 | + |
| 59 | + new_node = Node(node_height, value) |
| 60 | + |
| 61 | + for i in range(node_height): |
| 62 | + new_node.forward[i] = update[i].forward[i] |
| 63 | + update[i].forward[i] = new_node |
| 64 | + self.length += 1 |
| 65 | + |
| 66 | + def to_list(self): |
| 67 | + result = [] |
| 68 | + current = self.head.forward[0] |
| 69 | + while current: |
| 70 | + result.append(current.value) |
| 71 | + current = current.forward[0] |
| 72 | + return result |
0 commit comments