-
Notifications
You must be signed in to change notification settings - Fork 0
/
SkipList.java
104 lines (87 loc) · 1.79 KB
/
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package data_structures;
import java.util.*;
public class SkipList <T extends Comparable<T>>
{
class Node
{
Node next, down;
int level;
T value;
public Node(T v, int l, Node n, Node d)
{
value = v;
level = l;
next = n;
down = d;
}
}
Node head;
Random rand;
final static double p = 0.5;
public SkipList()
{
head = new Node(null, 0, null, null);
rand = new Random();
}
public int getRandomLevel()
{
int level = 0;
while(level <= head.level && rand.nextDouble() < 0.5)
level++;
return level;
}
public boolean add(T v)
{
if (search(v))
return false;
int lev = getRandomLevel();
if (lev > head.level)
head = new Node(null, lev, null, head);
Node cur = head, bottom = null;
while(cur != null)
{
Node next = cur.next;
if (next == null || next.value.compareTo(v) > 0)
{
if (cur.level <= lev)
{
Node nn = new Node(v, cur.level, next, null);
cur.next = nn;
if (bottom != null)
bottom.down = nn;
bottom = nn;
}
cur = cur.down;
}
else
cur = cur.next;
}
return true;
}
public boolean search(T key)
{
Node cur = head;
while(cur != null)
{
if (cur.value != null && cur.value.compareTo(key) == 0)
return true;
Node next = cur.next;
if (next == null || next.value.compareTo(key) > 0)
cur = cur.down;
else
cur = cur.next;
}
return false;
}
public void print()
{
Node h = head;
while(h != null)
{
Node c = h;
while(c != null) {System.out.print(c.value + ", ");c = c.next;}
System.out.println();
h = h.down;
}
}
}