Skip to content

Commit 4780d0e

Browse files
skip list done
1 parent e718fb4 commit 4780d0e

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import random
2+
3+
class SkipNode:
4+
def __init__(self, value, height):
5+
self.value = value
6+
self.next = [None] * height
7+
8+
class SkipList:
9+
def __init__(self, max_height=16):
10+
self.max_height = max_height
11+
12+
self.head = SkipNode(None, self.max_height)
13+
self.level = 1
14+
15+
def _random_height(self) -> int:
16+
height = 1
17+
while random.random() < 0.5 and height < self.max_height:
18+
height += 1
19+
return height
20+
21+
def insert(self, value) -> None:
22+
update = [None] * self.max_height
23+
current = self.head
24+
25+
for i in range(self.max_height - 1, -1, -1):
26+
while current.next[i] is not None and current.next[i].value < value:
27+
current = current.next[i]
28+
update[i] = current
29+
30+
node_height = self._random_height()
31+
new_node = SkipNode(value, node_height)
32+
33+
for i in range(node_height):
34+
new_node.next[i] = update[i].next[i]
35+
update[i].next[i] = new_node
36+
37+
def __contains__(self, value) -> bool:
38+
current = self.head
39+
40+
for i in range(self.max_height - 1, -1, -1):
41+
while current.next[i] is not None and current.next[i].value < value:
42+
current = current.next[i]
43+
44+
current = current.next[0]
45+
return current is not None and current.value == value
46+
47+
def to_list(self) -> list:
48+
result = []
49+
current = self.head.next[0]
50+
while current is not None:
51+
result.append(current.value)
52+
current = current.next[0]
53+
return result

0 commit comments

Comments
 (0)