← 中文资源

简体中文版本

泛型跳表

该资源提供 ts-skip-list-prob-p16 的中文技术参考,涵盖核心方法、参数说明与使用示例

阅读英文原文

实现说明

泛型跳表以类 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; } 在内。

常见问题

除了语言工具链还要下载什么吗?

除了这个语言的工具链,什么都不用再下载。

核心语句

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

代码示例

class SkipNode { val: number; next: SkipNode[]; constructor(val: number, level: number) { this.val = val; this.next = new Array(level + 1).fill(null); } }
class SkipList {
  private p: number; private maxLevel: number; private head: SkipNode; private level: number;
  constructor(p = 0.5, maxLevel = 16) { this.p = p; this.maxLevel = maxLevel; this.head = new SkipNode(-Infinity, maxLevel); this.level = 0; }
  private randomLevel(): number { let lvl = 0; while (Math.random() < this.p && lvl < this.maxLevel) lvl++; return lvl; }
  insert(val: number): void {
    const update: SkipNode[] = 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; }
  }
}