← 中文资源

简体中文版本

跳表概率有序集合(JavaScript)

用几何分布概率层级实现跳表,支持插入删除和搜索。

阅读英文原文

实现说明

逻辑集中在类 SkipNode、SkipList里。 迭代是嵌套的:for (let i = this.level; i >= 0; i--) { while (cur.next[i] && cur.next[i].val < val) cur = cur.ne… 框定这一趟,for (let i = 0; i <= lvl; i++) { node.next[i] = update[i].next[i]; update[i].next[i] = node; } 做逐项处理。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。

核心语句

randomLevel() { let lvl = 0; while (Math.random() < this.p && lvl < this.maxLevel) lvl++; return lvl; }

代码示例

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; }
  }
}