File tree Expand file tree Collapse file tree 1 file changed +86
-0
lines changed Expand file tree Collapse file tree 1 file changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Skiplist {
2
+
3
+ private Node head ;
4
+ private Random random ;
5
+
6
+ public Skiplist () {
7
+ this .head = new Node (-1 );
8
+ this .random = new Random ();
9
+ }
10
+
11
+ public boolean search (int target ) {
12
+ Node curr = head ;
13
+ while (curr != null ) {
14
+ while (curr .next != null && curr .next .val < target ) {
15
+ curr = curr .next ;
16
+ }
17
+ if (curr .next != null && curr .next .val == target ) {
18
+ return true ;
19
+ }
20
+ curr = curr .down ;
21
+ }
22
+ return false ;
23
+ }
24
+
25
+ public void add (int num ) {
26
+ Stack <Node > stack = new Stack <>();
27
+ Node curr = head ;
28
+ while (curr != null ) {
29
+ while (curr .next != null && curr .next .val < num ) {
30
+ curr = curr .next ;
31
+ }
32
+ stack .push (curr );
33
+ curr = curr .down ;
34
+ }
35
+ boolean newLevel = true ;
36
+ Node downNode = null ;
37
+ while (newLevel && !stack .isEmpty ()) {
38
+ curr = stack .pop ();
39
+ Node newNode = new Node (num );
40
+ newNode .next = curr .next ;
41
+ newNode .down = downNode ;
42
+ curr .next = newNode ;
43
+ downNode = curr .next ;
44
+ newLevel = random .nextDouble () < 0.5 ;
45
+ }
46
+ if (newLevel ) {
47
+ Node prevHead = head ;
48
+ head = new Node (-1 );
49
+ head .down = prevHead ;
50
+ }
51
+ }
52
+
53
+ public boolean erase (int num ) {
54
+ Node curr = head ;
55
+ boolean found = false ;
56
+ while (curr != null ) {
57
+ while (curr .next != null && curr .next .val < num ) {
58
+ curr = curr .next ;
59
+ }
60
+ if (curr .next != null && curr .next .val == num ) {
61
+ found = true ;
62
+ curr .next = curr .next .next ;
63
+ }
64
+ curr = curr .down ;
65
+ }
66
+ return found ;
67
+ }
68
+
69
+ private static class Node {
70
+ int val ;
71
+ Node next ;
72
+ Node down ;
73
+
74
+ public Node (int val ) {
75
+ this .val = val ;
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Your Skiplist object will be instantiated and called as such:
82
+ * Skiplist obj = new Skiplist();
83
+ * boolean param_1 = obj.search(target);
84
+ * obj.add(num);
85
+ * boolean param_3 = obj.erase(num);
86
+ */
You can’t perform that action at this time.
0 commit comments