server.h|t_zset.c
    数据结构定义

    1. // tips 跳跃表的核心思想: 用空间换时间,如:level[]、zskiplist.length\zskiplist.header等O(1)
    2. // 跳表节点
    3. /* ZSETs use a specialized version of Skiplists */
    4. typedef struct zskiplistNode {
    5. sds ele; // 节点元素内容,sds
    6. double score; // 分值: 从小到大排序
    7. struct zskiplistNode *backward; // 后退指针(前驱节点)
    8. struct zskiplistLevel {
    9. struct zskiplistNode *forward; // 前向指针(后继节点)或者说将next移至到level中
    10. unsigned long span; // 跨度, 即节点距离 ≥1
    11. } level[]; // 层数组: 数量越多访问越快 // tips 柔性数组
    12. } zskiplistNode;
    13. // 跳表 zskiplist
    14. // 链表节点(头节点、尾节点)
    15. // 长度length
    16. // 高度level
    17. typedef struct zskiplist {
    18. struct zskiplistNode *header, *tail; // 头、尾节点 头节点相当于航标
    19. unsigned long length; // 除头节点外的节点数
    20. int level; // 除头节点外的最大层数
    21. } zskiplist;

    API

    1. zskiplist *zslCreate(void);
    2. void zslFree(zskiplist *zsl);
    3. zskiplistNode *zslInsert(zskiplist *zsl, double score, sds ele);
    4. unsigned char *zzlInsert(unsigned char *zl, sds ele, double score);
    5. int zslDelete(zskiplist *zsl, double score, sds ele, zskiplistNode **node);
    6. zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range);
    7. zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range);

    内部函数

    1. zskiplistNode *zslCreateNode(int level, double score, sds ele);
    2. void zslFreeNode(zskiplistNode *node);
    3. void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update);
    4. // 获取随机层数
    5. int zslRandomLevel(void) {
    6. int level = 1;
    7. while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
    8. level += 1;
    9. return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
    10. }

    说明
    数据结构中
    创建:分配内存(在结构体中注意柔性数组内存分配)以及初始化变量(及成员变量)
    销毁:释放内存(或归还内存到内存池等),嵌套其他数据结构时也需释放、组合其他数据结构(如链表节点)时遍历释放,释放后指针指向NULL