redis链表

redis链表

  • 作用:实现list命令
  • 作为redis定时事件的实现方式
  • 服务器保存客户端列表等

数据结构

  • 双向非循环链表
// 链表节点
typedef struct listNode {
    struct listNode *prev; // 前驱
    struct listNode *next; // 后继
    void *value;  // 值
} listNode;

// 链表迭代器
typedef struct listIter {
    listNode *next; // 下一个节点
    int direction; // 迭代方向
} listIter;

// 迭代方向
#define AL_START_HEAD 0
#define AL_START_TAIL 1


// 链表定义
typedef struct list {
    listNode *head; // 链表头指针
    listNode *tail; // 链表尾指针
    void *(*dup)(void *ptr); // 节点值的复制函数
    void (*free)(void *ptr); // 节点值的释放函数
    int (*match)(void *ptr, void *key); // 节点值的匹配函数 
    unsigned long len; // 链表长度
} list;

相关宏定义

/* Functions implemented as macros */
#define listLength(l) ((l)->len) // 获取链表长度
#define listFirst(l) ((l)->head) // 获取链表头部节点
#define listLast(l) ((l)->tail) // 获取链表尾部节点
#define listPrevNode(n) ((n)->prev) // 获取某个节点的前驱节点
#define listNextNode(n) ((n)->next) // 获取某个节点的后继节点
#define listNodeValue(n) ((n)->value) // 获取某个节点的值

#define listSetDupMethod(l,m) ((l)->dup = (m))  // 设置节点复制函数
#define listSetFreeMethod(l,m) ((l)->free = (m)) // 设置节点释放函数
#define listSetMatchMethod(l,m) ((l)->match = (m))// 设置节点匹配函数

#define listGetDupMethod(l) ((l)->dup) // 获取节点复制函数
#define listGetFree(l) ((l)->free) // 获取节点释放函数
#define listGetMatchMethod(l) ((l)->match) // 获取节点匹配函数

功能函数实现

  • 函数原型
/* Prototypes */
list *listCreate(void);
void listRelease(list *list);
list *listAddNodeHead(list *list, void *value);
list *listAddNodeTail(list *list, void *value);
list *listInsertNode(list *list, listNode *old_node, void *value, int after);
void listDelNode(list *list, listNode *node);
listIter *listGetIterator(list *list, int direction);
listNode *listNext(listIter *iter);
void listReleaseIterator(listIter *iter);
list *listDup(list *orig);
listNode *listSearchKey(list *list, void *key);
listNode *listIndex(list *list, long index);
void listRewind(list *list, listIter *li);
void listRewindTail(list *list, listIter *li);
void listRotate(list *list);
  • 具体实现
/* Create a new list. The created list can be freed with
 * AlFreeList(), but private value of every node need to be freed
 * by the user before to call AlFreeList().
 *
 * On error, NULL is returned. Otherwise the pointer to the new list. */
 
// 创建链表
list *listCreate(void)
{
    struct list *list;
    // 分配内存
    if ((list = zmalloc(sizeof(*list))) == NULL)
        return NULL;
    // 初始化
    list->head = list->tail = NULL;
    list->len = 0;
    list->dup = NULL;
    list->free = NULL;
    list->match = NULL;
    return list;
}

/* Free the whole list.
 *
 * This function can't fail. */
// 释放链表
void listRelease(list *list)
{
    unsigned long len;
    listNode *current, *next;

    current = list->head;
    len = list->len; // 链表长度
    while(len--) {
        next = current->next;
        if (list->free) list->free(current->value); // 如果有值的释放函数调用
        zfree(current); // 释放内存
        current = next;
    }
    zfree(list); // 释放整个链表管理节点
}

/* Add a new node to the list, to head, containing the specified 'value'
 * pointer as value.
 *
 * On error, NULL is returned and no operation is performed (i.e. the
 * list remains unaltered).
 * On success the 'list' pointer you pass to the function is returned. */
// 头部增加节点
list *listAddNodeHead(list *list, void *value)
{
    listNode *node;
    // 为节点分配内存
    if ((node = zmalloc(sizeof(*node))) == NULL)
        return NULL;
    node->value = value;
    if (list->len == 0) { // 添加前链表为空
        list->head = list->tail = node;
        node->prev = node->next = NULL;
    } else {// 已经存在头节点
        node->prev = NULL;
        node->next = list->head;
        list->head->prev = node;
        list->head = node;
    }
    list->len++; // 增加长度
    return list;
}

/* Add a new node to the list, to tail, containing the specified 'value'
 * pointer as value.
 *
 * On error, NULL is returned and no operation is performed (i.e. the
 * list remains unaltered).
 * On success the 'list' pointer you pass to the function is returned. */
// 在链表尾部添加节点
list *listAddNodeTail(list *list, void *value)
{
    listNode *node;

    if ((node = zmalloc(sizeof(*node))) == NULL)
        return NULL;
    node->value = value;
    if (list->len == 0) { // 链表为空
        list->head = list->tail = node;
        node->prev = node->next = NULL;
    } else { // 链表非空
        node->prev = list->tail;
        node->next = NULL;
        list->tail->next = node;
        list->tail = node;
    }
    list->len++; // 增加长度
    return list;
}

// 在某个节点前(后)插入节点
list *listInsertNode(list *list, listNode *old_node, void *value, int after) {
    listNode *node;
    // 创建插入节点
    if ((node = zmalloc(sizeof(*node))) == NULL)
        return NULL;
    node->value = value;
    if (after) {// 节点之后插入
        node->prev = old_node;
        node->next = old_node->next;
        if (list->tail == old_node) { // 在尾部节点之后插入节点
            list->tail = node;
        }
    } else {// 节点之前插入
        node->next = old_node;
        node->prev = old_node->prev;
        if (list->head == old_node) {// 在头部部节点之前插入节点
            list->head = node;
        }
    }
    if (node->prev != NULL) { // 插入节点后,非头节点
        node->prev->next = node;
    }
    if (node->next != NULL) { // 插入节点后,非尾部节点
        node->next->prev = node;
    }
    list->len++;
    return list;
}

/* Remove the specified node from the specified list.
 * It's up to the caller to free the private value of the node.
 *
 * This function can't fail. */
 
// 删除某个节点
void listDelNode(list *list, listNode *node)
{
    if (node->prev) // 待删除节点有前驱节点
        node->prev->next = node->next;
    else // 删除头节点
        list->head = node->next;
    if (node->next)// 待删除节点有后继节点
        node->next->prev = node->prev;
    else // 删除尾节点
        list->tail = node->prev;
    if (list->free) list->free(node->value); // 释放值函数
    zfree(node); 
    list->len--; // 链表长度减1
}

/* Returns a list iterator 'iter'. After the initialization every
 * call to listNext() will return the next element of the list.
 *
 * This function can't fail. */
// 获取链表某个方向上的迭代器
listIter *listGetIterator(list *list, int direction)
{
    listIter *iter;

    if ((iter = zmalloc(sizeof(*iter))) == NULL) return NULL;
    if (direction == AL_START_HEAD)// 头部开始的迭代器
        iter->next = list->head;
    else// 尾部开始的迭代器
        iter->next = list->tail;
    iter->direction = direction; // 迭代器方向
    return iter;
}

/* Release the iterator memory */
// 释放迭代器内存
void listReleaseIterator(listIter *iter) {
    zfree(iter);
}

/* Create an iterator in the list private iterator structure */
// 关联迭代器和链表,从头部开始迭代
void listRewind(list *list, listIter *li) {
    li->next = list->head;
    li->direction = AL_START_HEAD;
}

// 关联迭代器和链表,从尾部开始迭代
void listRewindTail(list *list, listIter *li) {
    li->next = list->tail;
    li->direction = AL_START_TAIL;
}

/* Return the next element of an iterator.
 * It's valid to remove the currently returned element using
 * listDelNode(), but not to remove other elements.
 *
 * The function returns a pointer to the next element of the list,
 * or NULL if there are no more elements, so the classical usage patter
 * is:
 *
 * iter = listGetIterator(list,<direction>);
 * while ((node = listNext(iter)) != NULL) {
 *     doSomethingWith(listNodeValue(node));
 * }
 *
 * */
// 获取迭代器的下一个元素
listNode *listNext(listIter *iter)
{
    listNode *current = iter->next;

    if (current != NULL) {
        if (iter->direction == AL_START_HEAD) // 后向
            iter->next = current->next;
        else// 前向
            iter->next = current->prev;
    }
    return current;
}

/* Duplicate the whole list. On out of memory NULL is returned.
 * On success a copy of the original list is returned.
 *
 * The 'Dup' method set with listSetDupMethod() function is used
 * to copy the node value. Otherwise the same pointer value of
 * the original node is used as value of the copied node.
 *
 * The original list both on success or error is never modified. */
// 复制链表
list *listDup(list *orig)
{
    list *copy;
    listIter *iter;
    listNode *node;

    if ((copy = listCreate()) == NULL)
        return NULL;
    // 函数复制
    copy->dup = orig->dup;
    copy->free = orig->free;
    copy->match = orig->match;
    iter = listGetIterator(orig, AL_START_HEAD);
    while((node = listNext(iter)) != NULL) {
        void *value;

        if (copy->dup) {
            value = copy->dup(node->value);
            if (value == NULL) { // 复制节点值失败
                listRelease(copy);
                listReleaseIterator(iter);
                return NULL;
            }
        } else // 没有复制函数,那么复制后的链表指向复制前的链表
            value = node->value;
        if (listAddNodeTail(copy, value) == NULL) { // 添加节点到尾部
            listRelease(copy);
            listReleaseIterator(iter);
            return NULL;
        }
    }
    listReleaseIterator(iter);
    return copy;
}

/* Search the list for a node matching a given key.
 * The match is performed using the 'match' method
 * set with listSetMatchMethod(). If no 'match' method
 * is set, the 'value' pointer of every node is directly
 * compared with the 'key' pointer.
 *
 * On success the first matching node pointer is returned
 * (search starts from head). If no matching node exists
 * NULL is returned. */
// 查找链表
listNode *listSearchKey(list *list, void *key)
{
    listIter *iter;
    listNode *node;

    iter = listGetIterator(list, AL_START_HEAD);
    while((node = listNext(iter)) != NULL) {
        if (list->match) {// 值匹配函数
            if (list->match(node->value, key)) {
                listReleaseIterator(iter);
                return node;
            }
        } else { // 直接使用==
            if (key == node->value) {
                listReleaseIterator(iter);
                return node;
            }
        }
    }
    listReleaseIterator(iter);
    return NULL;
}

/* Return the element at the specified zero-based index
 * where 0 is the head, 1 is the element next to head
 * and so on. Negative integers are used in order to count
 * from the tail, -1 is the last element, -2 the penultimate
 * and so on. If the index is out of range NULL is returned. */
// 获取索引上的链表节点
listNode *listIndex(list *list, long index) {
    listNode *n;

    if (index < 0) { // 索引为负数,从尾部开始查找
        index = (-index)-1;
        n = list->tail;
        while(index-- && n) n = n->prev;
    } else { // 索引非负,从头部开始查找
        n = list->head;
        while(index-- && n) n = n->next;
    }
    return n;
}

/* Rotate the list removing the tail node and inserting it to the head. */
// 旋转链表,把尾部节点删除,插入到头部
void listRotate(list *list) {
    listNode *tail = list->tail;

    if (listLength(list) <= 1) return;

    /* Detach current tail */
    list->tail = tail->prev;
    list->tail->next = NULL;
    /* Move it as head */
    list->head->prev = tail;
    tail->prev = NULL;
    tail->next = list->head;
    list->head = tail;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • 链表的实现方式有很多种,常见的主要有三个,单向链表、双向链表、循环链表。 1、单链表 结构:第一个部分保存或者显示...
    多多的大白阅读 829评论 0 0
  • 链表作为一种常用的数据结构,提供了高效的节点重排能力,以及顺序性节点访问方式。并且可以通过增删来灵活的调整链表的长...
    binge1024阅读 733评论 0 0
  • 链表提供了高效的节点重排能力,以及顺序性的节点访问方式,并且可以通过增删节点来灵魂的调整链表长度。 链表和链表节点...
    我要尝鲜阅读 326评论 0 1
  • 链表结构是 Redis 中一个常用的结构,它可以存储多个字符串,而且它是有序的,能够存储 2 的 32 次方减 1...
    祐吢房_2c9a阅读 139评论 0 0
  •  链表:具有高效节点重排能力,顺序性节点访问,通过增删节点灵活调整长度。C语言中没有内置链表,Redis构建了自身...
    i孤独行者阅读 89评论 0 0