Skip to content

Commit 9024975

Browse files
authored
Update 1206-design-skiplist.js
1 parent 9a2f6f3 commit 9024975

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

1206-design-skiplist.js

+63
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,66 @@
1+
class Skiplist {
2+
constructor() {
3+
this.head = { down: null, right: null, val: -Infinity }
4+
}
5+
search(val) {
6+
let curr = this.head
7+
while (curr) {
8+
while (curr.right && curr.right.val <= val) {
9+
curr = curr.right
10+
}
11+
if (curr.val == val) {
12+
return true
13+
}
14+
curr = curr.down
15+
}
16+
return false
17+
}
18+
add(val) {
19+
let curr = this.head
20+
const insertion_positions = []
21+
while (curr) {
22+
while (curr.right && curr.right.val < val) {
23+
curr = curr.right
24+
}
25+
insertion_positions.push(curr)
26+
curr = curr.down
27+
}
28+
let insert = true
29+
let down = null
30+
while (insert && insertion_positions.length) {
31+
const position = insertion_positions.pop()
32+
const node = { down, val, right: position.right }
33+
position.right = node
34+
down = node
35+
insert = Math.random() < 0.5
36+
}
37+
if (insert) {
38+
const node = { val, down }
39+
this.head = { val: -Infinity, right: node, down: this.head }
40+
}
41+
}
42+
erase(val) {
43+
let curr = this.head
44+
const erase_positions = []
45+
while (curr) {
46+
while (curr.right && curr.right.val < val) {
47+
curr = curr.right
48+
}
49+
if (curr.right && curr.right.val == val) {
50+
erase_positions.push(curr)
51+
}
52+
curr = curr.down
53+
}
54+
const seen = erase_positions.length > 0
55+
for (const position of erase_positions) {
56+
position.right = position.right && position.right.right
57+
}
58+
return seen
59+
}
60+
}
61+
62+
// another
63+
164
const Skiplist = function () {
265
this.maxLvl = ~~Math.log2(20000)
366
this.levels = [...Array(this.maxLvl)].map(() => new Node(-1))

0 commit comments

Comments
 (0)