-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathDesign Skiplist.java
86 lines (78 loc) · 1.86 KB
/
Design Skiplist.java
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
class Skiplist {
private Node head;
private Random random;
public Skiplist() {
this.head = new Node(-1);
this.random = new Random();
}
public boolean search(int target) {
Node curr = head;
while (curr != null) {
while (curr.next != null && curr.next.val < target) {
curr = curr.next;
}
if (curr.next != null && curr.next.val == target) {
return true;
}
curr = curr.down;
}
return false;
}
public void add(int num) {
Stack<Node> stack = new Stack<>();
Node curr = head;
while (curr != null) {
while (curr.next != null && curr.next.val < num) {
curr = curr.next;
}
stack.push(curr);
curr = curr.down;
}
boolean newLevel = true;
Node downNode = null;
while (newLevel && !stack.isEmpty()) {
curr = stack.pop();
Node newNode = new Node(num);
newNode.next = curr.next;
newNode.down = downNode;
curr.next = newNode;
downNode = curr.next;
newLevel = random.nextDouble() < 0.5;
}
if (newLevel) {
Node prevHead = head;
head = new Node(-1);
head.down = prevHead;
}
}
public boolean erase(int num) {
Node curr = head;
boolean found = false;
while (curr != null) {
while (curr.next != null && curr.next.val < num) {
curr = curr.next;
}
if (curr.next != null && curr.next.val == num) {
found = true;
curr.next = curr.next.next;
}
curr = curr.down;
}
return found;
}
private static class Node {
int val;
Node next;
Node down;
public Node(int val) {
this.val = val;
}
}
}
/**
* Your Skiplist object will be instantiated and called as such:
* Skiplist obj = new Skiplist();
* boolean param_1 = obj.search(target);
* obj.add(num);
* boolean param_3 = obj.erase(num);
*/