Python 实现跳跃表查找(Skip List Search)算法
以下是用 Python 实现跳跃表查找(Skip List Search)算法的示例代码:
import random
class Node:
def __init__(self, value, level):
self.value = value
self.forward = [None] * (level + 1)
class SkipList:
def __init__(self, max_level):
self.max_level = max_level
self.head = Node(-1, max_level)
self.level = 0
def random_level(self):
level = 0
while random.random() < 0.5 and level < self.max_level:
level += 1
return level
def insert(self, value):
update = [None] * (self.max_level + 1)
current = self.head
for i in range(self.level, -1, -1):
while current.forward[i] and current.forward[i].value < value:
current = current.forward[i]
update[i] = current
lvl = self.random_level()
if lvl > self.level:
for i in range(self.level + 1, lvl + 1):
update[i] = self.head
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.head
for i in range(self.level, -1, -1):
while current.forward[i] and current.forward[i].value < value:
current = current.forward[i]
current = current.forward[0]
return current and current.value == value
# Test the SkipList implementation
skip_list = SkipList(16)
skip_list.insert(1)
skip_list.insert(3)
skip_list.insert(7)
skip_list.insert(8)
skip_list.insert(9)
print("Search for 3:", skip_list.search(3)) # Output: True
print("Search for 6:", skip_list.search(6)) # Output: False
这个 Python 实现包含了以下主要部分:
- Node 类:表示跳跃表中的节点,包含一个值和一个指针数组。
- SkipList 类:包含插入和查找方法,以及一个用于生成随机层级的
random_level
方法。 - random_level 方法:生成一个随机的层级,用于新节点。
- insert 方法:在跳跃表中插入一个值,更新相应的指针。
- search 方法:在跳跃表中查找一个值,返回一个布尔值表示是否找到。
这段代码展示了如何用 Python 实现跳跃表的插入和查找功能。