-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathskip_list.py
More file actions
52 lines (40 loc) · 1.46 KB
/
skip_list.py
File metadata and controls
52 lines (40 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
__author__ = 'yangbin1729'
import random
#TODO:跳表的实现
"""
跳表:
第一层为普通的链表,该层的每个元素有 p 的概率出现在第二层;
第二层相比第一层有更少的元素,且每个元素有 p 的概率出现在第三层;依次类推
"""
class SkipNode:
def __init__(self, height=0, elem=None):
self.elem = elem
self.next = [None] * height
class SkipList:
def __init__(self):
self.head = SkipNode()
def updateList(self, elem):
update = [None] * len(self.head.next)
x = self.head
for i in reversed(range(len(self.head.next))):
while x.next[i] != None and x.next[i].elem < elem:
x = x.next[i]
update[i] = x
return update
def find(self, elem, update=None):
if update == None:
update = self.updateList(elem)
if len(update) > 0:
candidate = update[0].next[0]
if candidate != None and candidate.elem == elem:
return candidate
return None
def insert(self, elem):
node = SkipNode(self.randomHeight(), elem)
while len(self.head.next) < len(node.next):
self.head.next.append(None)
update = self.updateList(elem)
if self.find(elem, update) == None:
for i in range(len(node.next)):
node.next[i] = update[i].next[i]
update[i].next[i] = None