Skip List Probabilistic Ordered Set (JavaScript)
Implement a skip list supporting insert, delete, and search with probabilistic level assignment using geometric distribution.
Code
class SkipNode {
constructor(val, level) { this.val = val; this.next = new Array(level + 1).fill(null); }
}
class SkipList {
constructor(p = 0.5, maxLevel = 16) { this.p = p; this.maxLevel = maxLevel; this.head = new SkipNode(-Infinity, maxLevel); this.level = 0; }
randomLevel() { let lvl = 0; while (Math.random() < this.p && lvl < this.maxLevel) lvl++; return lvl; }
insert(val) {
const update = new Array(this.maxLevel + 1).fill(this.head);
let cur = this.head;
for (let i = this.level; i >= 0; i--) { while (cur.next[i] && cur.next[i].val < val) cur = cur.next[i]; update[i] = cur; }
const lvl = this.randomLevel();
if (lvl > this.level) { for (let i = this.level + 1; i <= lvl; i++) update[i] = this.head; this.level = lvl; }
const node = new SkipNode(val, lvl);
for (let i = 0; i <= lvl; i++) { node.next[i] = update[i].next[i]; update[i].next[i] = node; }
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.