-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
SkipList.java
509 lines (448 loc) · 14.6 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
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package com.jwetherell.algorithms.data_structures;
import java.util.Random;
import com.jwetherell.algorithms.data_structures.interfaces.ISet;
/**
* Skip List. A skip list is a data structure for storing a sorted list of items
* using a hierarchy of linked lists that connect increasingly sparse
* subsequences of the items. These auxiliary lists allow item lookup with
* efficiency comparable to balanced binary search trees.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Skip_list">Skip List (Wikipedia)</a>
* <br>
* @author Justin Wetherell <[email protected]>
*/
@SuppressWarnings("unchecked")
public class SkipList<T extends Comparable<T>> implements ISet<T> {
private static final Random seedGenerator = new Random();
// If you change this number, you also need to change the random function.
private static final int MAX = 31;
private INodeCreator<T> creator = null;
private int randomSeed = -1;
private int size = 0;
protected Node<T> head = null;
public SkipList() {
randomSeed = seedGenerator.nextInt() | 0x0100;
}
public SkipList(INodeCreator<T> creator) {
this();
this.creator = creator;
}
/**
* Returns a random level for inserting a new node.
* Hardwired to k=1, p=0.5, max 31
*/
private int getRandom() {
int x = randomSeed;
x ^= x << 13;
x ^= x >>> 17;
randomSeed = x ^= x << 5;
if ((x & 0x8001) != 0) // test highest and lowest bits
return 0;
int level = 1;
while (((x >>>= 1) & 1) != 0) ++level;
return level;
}
protected Node<T> addValue(T value) {
Node<T> toReturn = null;
if (head==null) {
// new list
Node<T> node = null;
if (creator==null) node = new Node<T>(MAX,value);
else node = creator.createNewNode(MAX, value);
head = node;
toReturn = node;
} else {
int level = getRandom();
Node<T> node = null;
if (creator==null) node = new Node<T>(level,value);
else node = creator.createNewNode(level, value);
Node<T> prev = head;
if (head.data.compareTo(value)>0) {
// handle case where head is greater than new node, just swap values
//T oldHeadValue = head.data;
//head.data = value;
// Swap the old head value into the new node
//node.data = oldHeadValue;
if (creator==null) swapNode(node,head);
else creator.swapNode(node, head);
toReturn = head;
} else {
toReturn = node;
}
// Start from the top and work down to update the pointers
for (int i=MAX; i>=0; i--) {
Node<T> next = prev.getNext(i);
while (next!=null) {
if (next.data.compareTo(value)>0) break;
prev = next;
// It's important to set next since the node we are looking for
// on the next level cannot be behind this "prev" node.
next = prev.getNext(i);
}
if (i <= level) {
// If we are on a level where the new node exists, update the linked list
node.setNext(i, next);
prev.setNext(i, node);
}
}
}
size++;
return toReturn;
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(T value) {
Node<T> node = addValue(value);
return (node!=null);
}
private NodeLevelPair<T> getPredecessor(T value) {
Node<T> node = head;
if (node==null) return null;
if (node.data.compareTo(value)==0) return null;
// Current node is not the node we are looking for; Keep moving down
// until you find a node with a non-null "next" pointer.
int level = node.getLevel();
Node<T> next = node.getNext(level);
while (next==null) {
// If next is null, move down
if (level>0) next = node.getNext(--level);
else break;
}
// Found a node with a next node OR I reached the bottom level
while (next!=null) {
int comp = next.data.compareTo(value);
if (comp==0) {
// Found the node who's next node is the node we are looking for!
NodeLevelPair<T> pair = new NodeLevelPair<T>(level,node);
return pair;
} else if (comp>=1) {
// Found a node that's greater, move down a level
if (level>0) level--;
else return null;
// Update the next pointer
next = node.getNext(level);
} else {
// Next is less then the value we are looking for, keep moving to next.
node = next;
next = node.getNext(level);
while (next==null && level>0) {
next = node.getNext(--level);
}
}
}
return null;
}
protected Node<T> getNode(T value) {
if (head==null) return null;
if (head.data.compareTo(value)==0) return head;
NodeLevelPair<T> pair = getPredecessor(value);
if (pair==null) return null;
return pair.node.getNext(pair.level);
}
protected void swapNode(Node<T> node, Node<T> next) {
T value = node.data;
node.data = next.data;
next.data = value;
}
protected Node<T> removeValue(T value) {
if (head==null) return null;
Node<T> node = null;
Node<T> prev = null;
int lvl = 0;
if (head.data.compareTo(value)==0) {
node = head;
} else {
// Find the predecessor of the node we are looking for and
// which level it is found on.
NodeLevelPair<T> pair = getPredecessor(value);
if (pair!=null) {
prev = pair.node;
lvl = pair.level;
}
// Cannot find predecessor of value
if (prev == null)
return null;
// Use predecessor to get actual node
node = prev.getNext(lvl);
// Node doesn't exist
if (node == null || node.data.compareTo(value)!=0)
return null;
}
Node<T> next = null;
// Head node is the only node without a prev node
if (prev == null) {
next = node.getNext(0);
// Removing head
if (next != null) {
// Switch the value of the next into the head node
if (creator==null) swapNode(node,next);
else creator.swapNode(node, next);
// Update the prev and node pointer
prev = node;
node = next;
} else {
// If head doesn't have a new node then list is empty
head = null;
}
} else {
// Set the next node pointer
next = node.getNext(lvl);
}
// Start from the top level and move down removing the node
int level = node.getLevel();
for (int i=level; i>=0; i--) {
next = node.getNext(i);
if (prev!=null) {
prev.setNext(i, next);
if (i > 0) {
// Move down a level and look for the 'next' previous node
Node<T> temp = prev.getNext(i - 1);
while (temp != null && temp.data.compareTo(value) != 0) {
prev = temp;
temp = temp.getNext(i - 1);
}
}
}
}
size--;
return node;
}
/**
* {@inheritDoc}
*/
@Override
public boolean remove(T value) {
Node<T> node = removeValue(value);
return (node!=null);
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
head = null;
size = 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(T value) {
return (getNode(value)!=null);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return size;
}
/**
* {@inheritDoc}
*/
@Override
public boolean validate() {
if (head==null) return true;
int level = MAX;
for (int i=level; i>=0; i--) {
Node<T> prev = head;
Node<T> node = prev.getNext(i);
while (node != null) {
// The list should be ordered
if (node.data.compareTo(prev.data) < 1)
return false;
prev = node;
node = prev.getNext(i);
}
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Set<T> toSet() {
return (new JavaCompatibleSkipList<T>(this));
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Collection<T> toCollection() {
return (new JavaCompatibleSkipList<T>(this));
}
// Output a String version of the skip list. If a value and level is passed
// then output with that node highlighted.
public String getString(T value, int level) {
StringBuilder builder = new StringBuilder();
builder.append("size=").append(size).append("\n");
Node<T> node = head;
if (node!=null) {
int iLevel = node.getLevel();
for (int i=iLevel; i>=0; i--) {
builder.append("[").append(i).append("] ");
node = head;
while (node != null) {
if (level==i && value!=null && node.data.compareTo(value)==0)
builder.append("(").append(node.data).append(")");
else
builder.append(node.data);
Node<T> next = node.getNext(i);
if (next != null)
builder.append("->");
node = next;
}
if (i>0) builder.append("\n");
}
}
builder.append("\n");
return builder.toString();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return getString(null,-1);
}
protected static class Node<T extends Comparable<T>> {
private Node<T>[] next = null;
protected T data = null;
protected Node(int level, T data) {
this.next = new Node[level+1];
this.data = data;
}
protected int getLevel() {
return next.length-1;
}
protected void setNext(int idx, Node<T> node) {
this.next[idx] = node;
}
protected Node<T> getNext(int idx) {
if (idx>=this.next.length) return null;
return this.next[idx];
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("data=").append(data);
if (next!=null) {
builder.append("\n").append("next=[");
int size = next.length;
for (int i=0; i<size; i++) {
Node<T> n = next[i];
if (n!=null) builder.append(n.data);
else builder.append("none");
if (i!=size-1) builder.append(", ");
}
builder.append("]");
}
return builder.toString();
}
}
protected static interface INodeCreator<T extends Comparable<T>> {
/**
* Create a new Node with the following parameters.
*
* @param level of this node.
* @param data of this node.
* @return new Node
*/
public Node<T> createNewNode(int level, T data);
/**
* Swap the two nodes internals
*
* @param node to swap.
* @param next to swap.
*/
public void swapNode(Node<T> node, Node<T> next);
}
private static final class NodeLevelPair<T extends Comparable<T>> {
private int level = -1;
private Node<T> node = null;
private NodeLevelPair(int level, Node<T> node) {
this.level = level;
this.node = node;
}
}
public static class JavaCompatibleSkipList<T extends Comparable<T>> extends java.util.AbstractSet<T> {
private SkipList<T> list = null;
public JavaCompatibleSkipList(SkipList<T> list) {
this.list = list;
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(T value) {
return list.add(value);
}
/**
* {@inheritDoc}
*/
@Override
public boolean remove(Object value) {
return list.remove((T)value);
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(Object value) {
return list.contains((T)value);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return list.size();
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Iterator<T> iterator() {
return (new SkipListListIterator<T>(list));
}
private static class SkipListListIterator<T extends Comparable<T>> implements java.util.Iterator<T> {
private SkipList<T> list = null;
private SkipList.Node<T> next = null;
private SkipList.Node<T> last = null;
private SkipListListIterator(SkipList<T> list) {
this.list = list;
this.next = list.head;
}
/**
* {@inheritDoc}
*/
@Override
public void remove() {
if (last==null) return;
list.remove(last.data);
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
return (next!=null);
}
/**
* {@inheritDoc}
*/
@Override
public T next() {
if (next == null) throw new java.util.NoSuchElementException();
last = next;
next = next.getNext(0);
return last.data;
}
}
}
}