Redis学习篇 (2)linkedlist(双端链表)

redis
今天接着上一节 Redis学习篇 (1)SDS(Simple Dynamic String 简单动态字符串)来学习一下Redis的一个基本数据结构–linkedlist(双端链表),其定义和实现主要在adlist.hadlist.c文件中。其主要用在实现列表键、事务模块保存输入命令和服务器模块,订阅模块保存多个客户端等。

双端链表是 Redis 的列表键的底层实现之一。Redis在实现链表的时候,定义其为双端无环链表。

一、双端链表数据结构

/* Node, List, and Iterator are the only data structures used currently. */
/* 节点,列表和迭代器是当前唯一使用的数据结构。 */
/* 双端链表节点 */
typedef struct listNode {
    struct listNode *prev; // 前置节点 前驱指针
    struct listNode *next; // 后置节点 后继指针
    void *value; // 节点的值
} listNode;

/* 双端链表迭代器 */
typedef struct listIter {
    listNode *next; // 指向下一个节点
    int direction; // 迭代的方向
} listIter;
/* 双端链表结构 */
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;

list 结构为链表提供了表头指针 head, 表尾指针 tail, 以及链表长度的计数器 len. 来方便的对链表进行一个双端的遍历,或者查看链表长度。

下图是一个 list 结构,其中包含了三个 listNode:
list 结构

对于direction参数,Redis提供了两个宏定义

/* Directions for iterators */
#define AL_START_HEAD 0  // 从头到尾
#define AL_START_TAIL 1  // 从尾到头

二、函数的实现


//函数的实现

//返回给定链表所包含的节点数量
// T = O(1)
#define listLength(l) ((l)->len)

// 返回给定链表的表头节点
// T = O(1)
#define listFirst(l) ((l)->head)

// 返回给定链表的表尾节点
// T = O(1)
#define listLast(l) ((l)->tail)

// 返回给定节点的前置节点
// T = O(1)
#define listPrevNode(n) ((n)->prev)

// 返回给定节点的后置节点
// T = O(1)
#define listNextNode(n) ((n)->next)

// 返回给定节点的值
// T = O(1)
#define listNodeValue(n) ((n)->value)

// 将链表 l 的值复制函数设置为 m
// T = O(1)
#define listSetDupMethod(l,m) ((l)->dup = (m))

// 将链表 l 的值释放函数设置为 m
// T = O(1)
#define listSetFreeMethod(l,m) ((l)->free = (m))

// 将链表的对比函数设置为 m
// T = O(1)
#define listSetMatchMethod(l,m) ((l)->match = (m))

// 返回给定链表的值复制函数
// T = O(1)
#define listGetDupMethod(l) ((l)->dup)

// 返回给定链表的值释放函数
// T = O(1)
#define listGetFreeMethod(l) ((l)->free)

// 返回给定链表的值对比函数
// T = O(1)
#define listGetMatchMethod(l) ((l)->match)

三、链表实现文件

1、创建链表
/* Create a new list. The created list can be freed with
 * listRelease(), but private value of every node need to be freed
 * by the user before to call listRelease(), or by setting a free method using
 * listSetFreeMethod.
 *
 * On error, NULL is returned. Otherwise the pointer to the new list. */
 
/* 创建一个新的链表。
可以使用listRelease() 释放创建的列表,但是在调用listRelease()之前,用户必须释放每个节点的私有值,或者使用listSetFreeMethod设置一个自由方法。
错误时,返回NULL。 否则,指向新列表的指针。

T = O(1)
*/
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;
}
2、释放链表

/* Remove all the elements from the list without destroying the list itself. */
// 释放整个链表,以及链表中所有节点
// T = O(N)
void listEmpty(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;
    }
    list->head = list->tail = NULL;
    list->len = 0;
}
/* Free the whole list.
 *
 * This function can't fail. */
void listRelease(list *list)
{
    listEmpty(list);
    // 释放链表结构
    zfree(list);
}
3、链表添加新结点
/* 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. */
 
 /* 将一个包含有给定值指针 value 的新节点添加到链表的表头 
 错误时,返回NULL 并且不执行任何操作(即列表保持不变)。
 成功时,返回传递给函数的'list'指针。
 T = O(1)
 */
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++;

/* 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. */

/* 
将一个包含有给定值指针 value 的新节点添加到链表的表尾。
如果为新节点分配内存出错,那么不执行任何动作,仅返回 NULL。
如果执行成功,返回传入的链表指针。
T = O(1)
*/
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;
}
/*
 * 创建一个包含值 value 的新节点,并将它插入到 old_node 的之前或之后
 * old_node为插入位置
 * value为插入节点的值
 *
 * 如果 after 为 0 ,将新节点插入到 old_node 之前。
 * 如果 after 为 1 ,将新节点插入到 old_node 之后。
 * T = O(1)
*/
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;
       //  如果old_node为尾节点的话需要改变tail
        if (list->tail == old_node) {
            list->tail = node;
        }
    } else {
    // 向前插入
        node->next = old_node;
        node->prev = old_node->prev;
        // 如果old_node为头节点的话需要改变head
        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;
}

4、删除链表结点
/* 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. */
 /* 
 * 从链表 list 中删除给定节点 node 
 * 对节点私有值(private value of the node)的释放工作由调用者进行。
 * T = O(1)
 */
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);
    // 链表数减 1
    list->len--;
}
5、迭代器处理

sdlist为其迭代器提供了一些操作,用来完成获取(创建)迭代器,释放迭代器,重置迭代器,获取下一个迭代器等操作,具体源码见如下分析。


/* 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. */
/*
 * 为给定链表获取一个迭代器,
 * 之后每次对这个迭代器调用 listNext 都返回被迭代到的链表节点
 *
 * direction 参数决定了迭代器的迭代方向:
 *  AL_START_HEAD :从表头向表尾迭代
 *  AL_START_TAIL :从表尾想表头迭代
 *
 * T = O(1)
*/
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 */
/* 释放迭代器  T = O(1) */
void listReleaseIterator(listIter *iter) {
    zfree(iter);
}

// 重置迭代器
// 重置迭代器分为两种,一种是重置正向迭代器,一种是重置为逆向迭代器

/* Create an iterator in the list private iterator structure */
/* 重置为正向迭代器   T = O(1) */
void listRewind(list *list, listIter *li) {
    li->next = list->head;
    li->direction = AL_START_HEAD;
}
/* 重置为逆向迭代器  T = O(1) */
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
 * pattern is:
 *
 * iter = listGetIterator(list,<direction>);
 * while ((node = listNext(iter)) != NULL) {
 *     doSomethingWith(listNodeValue(node));
 * }
 *
 * */
 /*
 	返回迭代器的下一个元素。
 	使用listDelNode()删除当前返回的元素是有效的,但不能删除其他元素。
 	该函数返回指向列表的下一个元素的指针,如果没有更多元素,则返回NULL
*/
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;
}
6、其他链表函数

/* 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. */
/* 复制整个链表。
 *
 * 复制成功返回输入链表的副本,
 * 如果因为内存不足而造成复制失败,返回 NULL 。
 *
 * 如果链表有设置值复制函数 dup ,那么对值的复制将使用复制函数进行,
 * 否则,新节点将和旧节点共享同一个指针。
 *
 * 无论复制是成功还是失败,输入节点都不会修改。
 *
 * T = O(N)
 */

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;
    // 重置迭代器
    listRewind(orig, &iter);
    while((node = listNext(&iter)) != NULL) {
        void *value;
 		// 复制节点
        // 如果定义了dup函数,则按照dup函数来复制节点值
        if (copy->dup) {
            value = copy->dup(node->value);
            if (value == NULL) {
                listRelease(copy);
                return NULL;
            }
        } else
        	// 如果没有则直接赋值
            value = node->value;
		// 将节点添加到链表 ,依次向尾部添加节点
        if (listAddNodeTail(copy, value) == NULL) {
            listRelease(copy);
            return NULL;
        }
    }
    // 返回副本
    return copy;
}

// sdlist提供了两种查找函数。
// 其一是根据给定节点值,在链表中查找该节点
// 其二是根据序号来查找节点

/* 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. */
 /*
 * 查找链表 list 中值和 key 匹配的节点。 
 * 对比操作由链表的 match 函数负责进行,
 * 如果没有设置 match 函数,
 * 那么直接通过对比值的指针来决定是否匹配。
 * 如果匹配成功,那么第一个匹配的节点会被返回。
 * 如果没有匹配任何节点,那么返回 NULL 。
 *
 * T = O(N)
*/
listNode *listSearchKey(list *list, void *key)
{
    listIter iter;
    listNode *node;

    listRewind(list, &iter);
    while((node = listNext(&iter)) != NULL) {
        if (list->match) {
        	// 如果定义了match匹配函数,则利用该函数进行节点匹配
            if (list->match(node->value, key)) {
                return node;
            }
        } else {
            // 如果没有定义match,则直接比较节点值
            if (key == node->value) {
                return node;
            }
        }
    }
    // 没有找到就返回NULL
    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. */
 /*
 * 返回链表在给定索引上的值。
 *
 * 索引以 0 为起始,也可以是负数, -1 表示链表最后一个节点,诸如此类。
 * 如果索引超出范围(out of range),返回 NULL。
 *
 * T = O(N)
 */
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. */
/* 旋转列表,删除尾节点并将其插入到头部。 T = O(1) */
void listRotateTailToHead(list *list) {
    if (listLength(list) <= 1) return;

    /* Detach current tail */
    listNode *tail = list->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;
}

/* Rotate the list removing the head node and inserting it to the tail. */
/* 旋转列表,删除头节点并将其插入尾部。 T = O(1) */
void listRotateHeadToTail(list *list) {
    if (listLength(list) <= 1) return;

    listNode *head = list->head;
    /* Detach current head */
    list->head = head->next;
    list->head->prev = NULL;
    /* Move it as tail */
    list->tail->next = head;
    head->next = NULL;
    head->prev = list->tail;
    list->tail = head;
}

/* Add all the elements of the list 'o' at the end of the
 * list 'l'. The list 'other' remains empty but otherwise valid. */

/* 列表连接。 在列表“l”的末尾添加列表“o”的所有元素。 列表“其他”保持为空,但其他方式有效。T = O(1)  */
void listJoin(list *l, list *o) {
    if (o->len == 0) return;

    o->head->prev = l->tail;

    if (l->tail)
        l->tail->next = o->head;
    else
        l->head = o->head;

    l->tail = o->tail;
    l->len += o->len;

    /* Setup other as an empty list. */
    o->head = o->tail = NULL;
    o->len = 0;
}

四、优劣

  • 双向链表
    从 listNode 的结构我们可以看到,包含了前直接点和后置节点。因此通过迭代器可以很方便的对链表从从头至尾或从尾至头遍历。

  • 无环链表
    表头结点的 prev 指针和表尾结点的 next 指针都只想 null, 所以 Redis 的链表是一个无环链表。

  • 带有头指针和尾指针
    在 list 结构中,保存了当前链表的表头指针和表尾指针,因此可以快速的从头进行遍历或者从尾部开始遍历。高效地实现了Redis中一些指令的操作。

  • 带有长度计数器
    list 结构中保存了当前链表长度的长度,因此对链表长度的统计时间复杂度是 O(1)。

五、总结

链表是一个比较常用的数据结构,在很多编程语言中都有实现,读者们接触也很多。因此本文没有专门去强调它的实现方法,而是大概介绍了下 Redis 中的链表的一个结构及其主要特性:

  • Redis 的链表是双端链表。
  • 封装了 list 结构,保存了链表的头尾指针以及链表长度。
  • Redis 的链表是无环链表。


END

如有问题请在下方留言。

或关注我的公众号“孙三苗”,输入“联系方式”。获得进一步帮助。

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值