引言
跳跃表是redis集合的底层结构,是一种有序的数据结构。跳跃表查找单个节点的时间复杂度平均是O(logN),并且在查找相邻的一组节点的时候,其时间复杂度也是O(logN),相比于平衡树,虽然跳跃表的空间复杂度略大,但是在查询一组节点以及实现难度上要远远优于平衡树。
跳跃表的结构
结构部分可以参考https://blog.csdn.net/sssxlxwbwz/article/details/123769262
跳跃表插入与删除的实现
先来看看跳跃表定义的结构
/* ZSETs use a specialized version of Skiplists */
/*
* 跳跃表节点
*/
typedef struct zskiplistNode {
// 成员对象
robj *obj;
// 分值
double score;
// 后退指针
struct zskiplistNode *backward;
// 层
struct zskiplistLevel {
// 前进指针
struct zskiplistNode *forward;
// 跨度
unsigned int span;
} level[];
} zskiplistNode;
/*
* 跳跃表
*/
typedef struct zskiplist {
// 表头节点和表尾节点
struct zskiplistNode *header, *tail;
// 表中节点的数量
unsigned long length;
// 表中层数最大的节点的层数
int level;
} zskiplist;
插入
跳跃表的插入主要分为三个步骤,
(1):从上到下,从左往右遍历跳跃表,找到对应节点的前继节点的位置
(2):创建新节点,并随机产生层高
(3):将该节点插入跳跃表相应位置,并且更新前后字段值
/*
* 创建一个成员为 obj ,分值为 score 的新节点,
* 并将这个新节点插入到跳跃表 zsl 中。
*
* 函数的返回值为新节点。
*
* T_wrost = O(N^2), T_avg = O(N log N)
*/
zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj) {
//插入节点所要修改的前驱节点
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
//插入点前继节点在跳跃表中的位置,用来计算span
unsigned int rank[ZSKIPLIST_MAXLEVEL];
int i, level;
redisAssert(!isnan(score));
// 在各个层查找节点的插入位置
// T_wrost = O(N^2), T_avg = O(N log N)
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
/* store rank that is crossed to reach the insert position */
// 如果 i 不是 zsl->level-1 层
// 那么 i 层的起始 rank 值为 i+1 层的 rank 值
// 各个层的 rank 值一层层累积
// 最终 rank[0] 的值加一就是新节点的前置节点的排位
// rank[0] 会在后面成为计算 span 值和 rank 值的基础
rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
// 沿着前进指针遍历跳跃表
// T_wrost = O(N^2), T_avg = O(N log N)
while (x->level[i].forward &&
(x->level[i].forward->score < score ||
// 比对分值
(x->level[i].forward->score == score &&
// 比对成员, T = O(N)
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.
*
* zslInsert() 的调用者会确保同分值且同成员的元素不会出现,
* 所以这里不需要进一步进行检查,可以直接创建新元素。
*/
// 获取一个随机值作为新节点的层数
// T = O(N)
level = zslRandomLevel();
// 如果新节点的层数比表中其他节点的层数都要大
// 那么初始化表头节点中未使用的层,并将它们记录到 update 数组中
// 将来也指向新节点
if (level > zsl->level) {
// 初始化未使用层
// T = O(1)
for (i = zsl->level; i < level; i++) {
rank[i] = 0;
update[i] = zsl->header;
update[i]->level[i].span = zsl->length;
}
// 更新表中节点最大层数
zsl->level = level;
}
// 创建新节点
x = zslCreateNode(level,score,obj);
// 将前面记录的指针指向新节点,并做相应的设置
// T = O(1)
for (i = 0; i < level; i++) {
// 设置新节点的 forward 指针
x->level[i].forward = update[i]->level[i].forward;
// 将沿途记录的各个节点的 forward 指针指向新节点
update[i]->level[i].forward = x;
/* update span covered by update[i] as x is inserted here */
// 计算新节点跨越的节点数量
x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]);
// 更新新节点插入之后,沿途节点的 span 值
// 其中的 +1 计算的是新节点
update[i]->level[i].span = (rank[0] - rank[i]) + 1;
}
/* increment span for untouched levels */
// 未接触的节点的 span 值也需要增一,这些节点直接从表头指向新节点
// T = O(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;
// 跳跃表的节点计数增一
zsl->length++;
return x;
}
删除
/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank
*
* 内部删除函数,
* 被 zslDelete 、 zslDeleteRangeByScore 和 zslDeleteByRank 等函数调用。
*
* T = O(1)
*/
void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
int i;
// 更新所有和被删除节点 x 有关的节点的指针,解除它们之间的关系
// T = O(1)
for (i = 0; i < zsl->level; i++) {
if (update[i]->level[i].forward == x) {
//删除了节点后span需要减掉被删除的节点
update[i]->level[i].span += x->level[i].span - 1;
update[i]->level[i].forward = x->level[i].forward;
} else {
update[i]->level[i].span -= 1;
}
}
// 更新被删除节点 x 的前进和后退指针
if (x->level[0].forward) {
x->level[0].forward->backward = x->backward;
} else {
//删除节点在尾部
zsl->tail = x->backward;
}
// 更新跳跃表最大层数(只在被删除节点是跳跃表中最高的节点时才执行)
// T = O(1)
while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
zsl->level--;
// 跳跃表节点计数器减一
zsl->length--;
}
/* Delete an element with matching score/object from the skiplist.
*
* 从跳跃表 zsl 中删除包含给定节点 score 并且带有指定对象 obj 的节点。
*
* T_wrost = O(N^2), T_avg = O(N log N)
*/
int zslDelete(zskiplist *zsl, double score, robj *obj) {
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
int i;
// 遍历跳跃表,查找目标节点,并记录所有沿途节点
// T_wrost = O(N^2), T_avg = O(N log N)
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
// 遍历跳跃表的复杂度为 T_wrost = O(N), T_avg = O(log N)
while (x->level[i].forward &&
(x->level[i].forward->score < score ||
// 比对分值
(x->level[i].forward->score == score &&
// 比对对象,T = O(N)
compareStringObjects(x->level[i].forward->obj,obj) < 0)))
// 沿着前进指针移动
x = x->level[i].forward;
// 记录沿途节点
update[i] = x;
}
/* We may have multiple elements with the same score, what we need
* is to find the element with both the right score and object.
*
* 检查找到的元素 x ,只有在它的分值和对象都相同时,才将它删除。
*/
x = x->level[0].forward;
if (x && score == x->score && equalStringObjects(x->obj,obj)) {
// T = O(1)
zslDeleteNode(zsl, x, update);
// T = O(1)
zslFreeNode(x);
return 1;
} else {
return 0; /* not found */
}
return 0; /* not found */
}
跳跃表的范围查询
表示跳跃表数值范围的数据结构:
/* Struct to hold a inclusive/exclusive range spec by score comparison. */
// 表示开区间/闭区间范围的结构
typedef struct {
// 最小值和最大值
double min, max;
// 指示最小值和最大值是否*不*包含在范围之内
// 值为 1 表示不包含,值为 0 表示包含
int minex, maxex; /* are min or max exclusive? */
} zrangespec;
查找第一个符合条件的节点(zslFirstInRange)与最后一个符合条件的节点(zslLastInRange)
/*
* 检测给定值 value 是否大于(或大于等于)范围 spec 中的 min 项。
*
* 返回 1 表示 value 大于等于 min 项,否则返回 0 。
*
* T = O(1)
*/
static int zslValueGteMin(double value, zrangespec *spec) {
return spec->minex ? (value > spec->min) : (value >= spec->min);
}
/*
* 检测给定值 value 是否小于(或小于等于)范围 spec 中的 max 项。
*
* 返回 1 表示 value 小于等于 max 项,否则返回 0 。
*
* T = O(1)
*/
static int zslValueLteMax(double value, zrangespec *spec) {
return spec->maxex ? (value < spec->max) : (value <= spec->max);
}
/* Find the first node that is contained in the specified range.
*
* 返回 zsl 中第一个分值符合 range 中指定范围的节点。
* Returns NULL when no element is contained in the range.
*
* 如果 zsl 中没有符合范围的节点,返回 NULL 。
*
* T_wrost = O(N), T_avg = O(log N)
*/
zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range) {
zskiplistNode *x;
int i;
/* If everything is out of range, return early. */
if (!zslIsInRange(zsl,range)) return NULL;
// 遍历跳跃表,查找符合范围 min 项的节点
// T_wrost = O(N), T_avg = O(log N)
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *OUT* of range. */
while (x->level[i].forward &&
!zslValueGteMin(x->level[i].forward->score,range))
x = x->level[i].forward;
}
/* This is an inner range, so the next node cannot be NULL. */
x = x->level[0].forward;
redisAssert(x != NULL);
/* Check if score <= max. */
// 检查节点是否符合范围的 max 项
// T = O(1)
if (!zslValueLteMax(x->score,range)) return NULL;
return x;
}
/* Find the last node that is contained in the specified range.
* Returns NULL when no element is contained in the range.
*
* 返回 zsl 中最后一个分值符合 range 中指定范围的节点。
*
* 如果 zsl 中没有符合范围的节点,返回 NULL 。
*
* T_wrost = O(N), T_avg = O(log N)
*/
zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range) {
zskiplistNode *x;
int i;
/* If everything is out of range, return early. */
// 先确保跳跃表中至少有一个节点符合 range 指定的范围,
// 否则直接失败
// T = O(1)
if (!zslIsInRange(zsl,range)) return NULL;
// 遍历跳跃表,查找符合范围 max 项的节点
// T_wrost = O(N), T_avg = O(log N)
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *IN* range. */
while (x->level[i].forward &&
zslValueLteMax(x->level[i].forward->score,range))
x = x->level[i].forward;
}
/* This is an inner range, so this node cannot be NULL. */
redisAssert(x != NULL);
/* Check if score >= min. */
// 检查节点是否符合范围的 min 项
// T = O(1)
if (!zslValueGteMin(x->score,range)) return NULL;
// 返回节点
return x;
}
跳跃表的范围删除
/* Delete all the elements with score between min and max from the skiplist.
*
* 删除所有分值在给定范围之内的节点。
*
* Min and max are inclusive, so a score >= min || score <= max is deleted.
*
* min 和 max 参数都是包含在范围之内的,所以分值 >= min 或 <= max 的节点都会被删除。
*
* Note that this function takes the reference to the hash table view of the
* sorted set, in order to remove the elements from the hash table too.
*
* 节点不仅会从跳跃表中删除,而且会从相应的字典中删除。
*
* 返回值为被删除节点的数量
*
* T = O(N)
*/
unsigned long zslDeleteRangeByScore(zskiplist *zsl, zrangespec *range, dict *dict) {
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
unsigned long removed = 0;
int i;
// 记录所有和被删除节点(们)有关的节点
// T_wrost = O(N) , T_avg = O(log N)
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward && (range->minex ?
x->level[i].forward->score <= range->min :
x->level[i].forward->score < range->min))
x = x->level[i].forward;
update[i] = x;
}
/* Current node is the last with score < or <= min. */
// 定位到给定范围开始的第一个节点
x = x->level[0].forward;
/* Delete nodes while in range. */
// 删除范围中的所有节点
// T = O(N)
while (x &&
(range->maxex ? x->score < range->max : x->score <= range->max))
{
// 记录下个节点的指针
zskiplistNode *next = x->level[0].forward;
zslDeleteNode(zsl,x,update);
dictDelete(dict,x->obj);
zslFreeNode(x);
removed++;
x = next;
}
return removed;
}
/* Delete all the elements with rank between start and end from the skiplist.
*
* 从跳跃表中删除所有给定排位内的节点。
*
* Start and end are inclusive. Note that start and end need to be 1-based
*
* start 和 end 两个位置都是包含在内的。注意它们都是以 1 为起始值。
*
* 函数的返回值为被删除节点的数量。
*
* T = O(N)
*/
unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
unsigned long traversed = 0, removed = 0;
int i;
// 沿着前进指针移动到指定排位的起始位置,并记录所有沿途指针
// T_wrost = O(N) , T_avg = O(log N)
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward && (traversed + x->level[i].span) < start) {
traversed += x->level[i].span;
x = x->level[i].forward;
}
update[i] = x;
}
// 移动到排位的起始的第一个节点
traversed++;
x = x->level[0].forward;
// 删除所有在给定排位范围内的节点
// T = O(N)
while (x && traversed <= end) {
// 记录下一节点的指针
zskiplistNode *next = x->level[0].forward;
// 从跳跃表中删除节点
zslDeleteNode(zsl,x,update);
// 从字典中删除节点
dictDelete(dict,x->obj);
// 释放节点结构
zslFreeNode(x);
// 为删除计数器增一
removed++;
// 为排位计数器增一
traversed++;
// 处理下个节点
x = next;
}
// 返回被删除节点的数量
return removed;
}
删除的逻辑都比较简单,这里也不再赘述。