-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram-8.cpp
More file actions
99 lines (73 loc) · 1.67 KB
/
program-8.cpp
File metadata and controls
99 lines (73 loc) · 1.67 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
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
/*
Skip List Implementation
*/
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAXLVL = 3;
class Node {
public:
int val;
Node* forward[MAXLVL + 1];
Node(int v) {
val = v;
for (int i = 0; i <= MAXLVL; i++)
forward[i] = NULL;
}
};
class SkipList {
Node* header;
int level;
public:
SkipList() {
level = 0;
header = new Node(-1);
}
int randomLevel() {
int lvl = 0;
while (rand() % 2 && lvl < MAXLVL)
lvl++;
return lvl;
}
void insert(int val) {
Node* update[MAXLVL + 1];
Node* cur = header;
for (int i = level; i >= 0; i--) {
while (cur->forward[i] && cur->forward[i]->val < val)
cur = cur->forward[i];
update[i] = cur;
}
cur = cur->forward[0];
if (!cur || cur->val != val) {
int rlevel = randomLevel();
if (rlevel > level) {
for (int i = level + 1; i <= rlevel; i++)
update[i] = header;
level = rlevel;
}
Node* n = new Node(val);
for (int i = 0; i <= rlevel; i++) {
n->forward[i] = update[i]->forward[i];
update[i]->forward[i] = n;
}
}
}
void display() {
Node* node = header->forward[0];
while (node) {
cout << node->val << " ";
node = node->forward[0];
}
}
};
int main() {
SkipList s;
int n, x;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
s.insert(x);
}
s.display();
return 0;
}