/
skipList.go
144 lines (118 loc) · 2.17 KB
/
skipList.go
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package skipList
import (
"errors"
"fmt"
"math"
"math/rand"
)
const (
MAXLEVEL = 16
MAXROUND = 65536
)
type Node struct {
key int
value interface{}
next [MAXLEVEL]*Node
}
type SkipList struct {
head *Node
tail *Node
size int
level int
}
func randLevel() int {
return MAXLEVEL - int(math.Log2(1.0+MAXROUND*rand.Float64()))
}
func NewNode(newKey int, newVal interface{}) *Node {
return &Node{
key: newKey,
value: newVal,
next: [MAXLEVEL]*Node{},
}
}
func NewSkipList() *SkipList {
s := new(SkipList)
s.head = NewNode(math.MinInt64, nil)
s.tail = NewNode(math.MaxInt64, nil)
for i := 0; i < MAXLEVEL; i++ {
s.head.next[i] = s.tail
}
s.size = 0
s.level = 1
return s
}
func (s *SkipList) Search(key int) (*Node, error) {
cur := s.head
for i := s.level - 1; i >= 0; i-- {
for cur.next[i].key < key {
cur = cur.next[i]
}
if cur.next[i].key == key {
return cur.next[i], nil
}
}
return nil, errors.New("Not Found.")
}
func (s *SkipList) Add(key int, newVal interface{}) {
pre := make([]*Node, MAXLEVEL)
cur := s.head
for i := s.level - 1; i >= 0; i-- {
for cur.next[i].key < key {
cur = cur.next[i]
}
pre[i] = cur
}
level := randLevel()
newNode := NewNode(key, newVal)
for i := 0; i < level; i++ {
if pre[i] == nil {
pre[i] = s.head
}
pre[i].next[i], newNode.next[i] = newNode, pre[i].next[i]
}
if s.level < level {
s.level = level
}
s.size++
}
func (s *SkipList) Erase(key int) (result bool) {
result = false
cur := s.head
for i := s.level - 1; i >= 0; i-- {
for cur.next[i].key < key {
cur = cur.next[i]
}
if cur.next[i].key == key {
tmp := cur.next[i]
cur.next[i] = cur.next[i].next[i]
tmp.next[i] = nil
result = true
}
}
if result {
s.size--
}
return
}
func (s *SkipList) Get(key int) (*Node, error) {
cur := s.head
for i := s.level - 1; i >= 0; i-- {
for cur.next[i].key < key {
cur = cur.next[i]
}
if cur.next[i].key == key {
return cur.next[i], nil
}
}
return nil, errors.New("Not Found.")
}
func (s *SkipList) Print() {
cur := s.head
for cur != nil {
fmt.Println(cur.value)
cur = cur.next[0]
}
}
func (s *SkipList) GetSize() int {
return s.size
}