-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesignSkiplist.cpp
More file actions
80 lines (70 loc) · 2.07 KB
/
designSkiplist.cpp
File metadata and controls
80 lines (70 loc) · 2.07 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
// Source: https://leetcode.com/problems/design-skiplist/
// Author: Miao Zhang
// Date: 2021-04-17
class Skiplist {
public:
Skiplist() {
head_ = make_shared<Node>();
}
bool search(int target) {
for (auto node = head_; node; node = node->down) {
while (node->next && node->next->val < target) {
node = node->next;
}
if (node->next && node->next->val == target)
return true;
}
return false;
}
void add(int num) {
stack<shared_ptr<Node>> st;
shared_ptr<Node> down;
bool insert = true;
for (auto node = head_; node; node = node->down) {
while (node->next && node->next->val < num) {
node = node->next;
}
st.push(node);
}
while (!st.empty() && insert) {
auto cur = st.top(); st.pop();
cur->next = make_shared<Node>(num, cur->next, down);
down = cur->next;
insert = rand() & 1;
}
if (insert) {
head_ = make_shared<Node>(-1, nullptr, head_);
}
}
bool erase(int num) {
bool found = false;
for (auto node = head_; node; node = node->down) {
while (node->next && node->next->val < num) {
node = node->next;
}
if (node->next && node->next->val == num) {
found = true;
node->next = node->next->next;
}
}
return found;
}
private:
struct Node {
Node (int val = -1,
shared_ptr<Node> next = nullptr,
shared_ptr<Node> down = nullptr) :
val(val), next(next), down(down) {}
int val;
shared_ptr<Node> next;
shared_ptr<Node> down;
};
shared_ptr<Node> head_;
};
/**
* Your Skiplist object will be instantiated and called as such:
* Skiplist* obj = new Skiplist();
* bool param_1 = obj->search(target);
* obj->add(num);
* bool param_3 = obj->erase(num);
*/