1. 跳跃表定义
是一种有序数据结构,通过每个节点中维持多个指向其他节点的指针,从而快速访问节点的目的. 查找节点复杂度 平均O(logN)\
最坏O(N),大部分情况跳跃表的效率可以和平衡数相媲美,实现更简单.
2. redis使用跳跃表最为有序集合键的底层实现之一,当有序集合元素数量多,或者成员是比较长的字符串,redis使用跳跃表
3. 跳跃表示例
4. zskiplist结构
typedef struct zskiplist {
//头尾节点
struct zskiplistNode *header, *tail;
//表中节点的数量
unsigned long length;
//表中层数最大的节点的层数
int level;
} zskiplist;
5.节点zskiplistNode
typedef struct zskiplistNode {
//成员变量
robj *obj;
//分值,各节点按各自保存的分支从小到大排列
double score;
//后退指针
struct zskiplistNode *backward;
//level 存储各层,用L1,L2等表示
struct zskiplistLevel {
//每个层
//前进指针
struct zskiplistNode *forward;
//跨度
unsigned int span;
} level[];
} zskiplistNode;
6. 插入节点zslInsert源码
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
//记录跨度和,提供 新插入节点跨度计算
unsigned int rank[ZSKIPLIST_MAXLEVEL];
int i, level;
redisAssert(!isnan(score));
//获取头节点
x = zsl->header;
//从最高层开始向下遍历
for (i = zsl->level-1; i >= 0; i--) {
/* store rank that is crossed to reach the insert position */
//记录上层的值
rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
//寻找插入节点的回退节点
//回退节点必须有前进节点,
while (x->level[i].forward &&
(x->level[i].forward->score < score ||
(x->level[i].forward->score == score &&
compareStringObjects(x->level[i].forward->obj,obj) < 0))) {
//跨度累加
rank[i] += x->level[i].span;
x = x->level[i].forward;
}
update[i] = x;
}
/* we assume the key is not already inside, since we allow duplicated
* scores, and the re-insertion of score and redis object should never
* happen since the caller of zslInsert() should test in the hash table
* if the element is already inside or not. */
//随机一个层数
level = zslRandomLevel();
//随机的层数大于现有的层数
if (level > zsl->level) {
//遍历没有的层数
for (i = zsl->level; i < level; i++) {
//更新
rank[i] = 0;
update[i] = zsl->header;
update[i]->level[i].span = zsl->length;
}
//更新list的层数
zsl->level = level;
}
//创建节点
x = zslCreateNode(level,score,obj);
//遍历新节点的层数
for (i = 0; i < level; i++) {
//插入新节点(通过修改前进和回退指针 插入)
x->level[i].forward = update[i]->level[i].forward;
update[i]->level[i].forward = x;
//插入结束
/* update span covered by update[i] as x is inserted here */
//更新 新节点的跨度
//rank[0] - rank[i] 解决每个节点 层数不同,带来的跨度不同
x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]);
//更新 新节点的回退节点的跨度
update[i]->level[i].span = (rank[0] - rank[i]) + 1;
}
/* increment span for untouched levels */
//随机的层数如果小于最高层,新节点回退节点的跨度加1
for (i = level; i < zsl->level; i++) {
update[i]->level[i].span++;
}
//更新头尾指针
x->backward = (update[0] == zsl->header) ? NULL : update[0];
if (x->level[0].forward)
x->level[0].forward->backward = x;
else
zsl->tail = x;
//节点数量加1
zsl->length++;
return x;
}