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 实现包含了以下主要部分:
random_level
方法。这段代码展示了如何用 Python 实现跳跃表的插入和查找功能。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。