双端链表在Redis中的地位:它作为一种通用数据结构,在Redis的内部使用非常多。是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 list {
// 表头指针
listNode *head;
// 表尾指针
listNode *tail;
// 节点数量
unsigned long len;
// 复制函数
void *(*dup)(void *ptr);
// 释放函数
void (*free)(void *ptr);
// 比对函数
int (*match)(void *ptr, void *key);
} list;
| 函数 | 作用 | 算法复杂度 |
|---|---|---|
| listCreate | 创建新链表 |
|
| listRelease | 释放链表,以及该链表所包含的节点 |
|
| listDup | 创建给定链表的副本 |
|
| listRotate | 取出链表的表尾节点,并插入到表头 |
|
| listAddNodeHead | 将包含给定值的节点添加到链表的表头 |
|
| listAddNodeTail | 将包含给定值的节点添加到链表的表尾 |
|
| listInsertNode | 将包含给定值的节点添加到某个节点的之前或之后 |
|
| listDelNode | 删除给定节点 |
|
| listSearchKey | 在链表中查找和给定 key 匹配的节点 |
|
| listIndex | 给据给定索引,返回列表中相应的节点 |
|
| listLength | 返回给定链表的节点数量 |
|
| listFirst | 返回链表的表头节点 |
|
| listLast | 返回链表的表尾节点 |
|
| listPrevNode | 返回给定节点的前一个节点 |
|
| listNextNode | 返回给定节点的后一个节点 |
|
| listNodeValue | 返回给定节点的值 |
|
/*
* 链表迭代器
*/
typedef struct listIter {
// 下一节点
listNode *next;
// 迭代方向
int direction;
} listIter;/*
* 创建列表 list 的一个迭代器,迭代方向由参数 direction 决定
*
* 每次对迭代器调用 listNext() ,迭代器就返回列表的下一个节点
*
* 这个函数不处理失败情形
*
* 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;
}| 函数 | 作用 | 算法复杂度 |
|---|---|---|
| listGetIterator | 创建一个列表迭代器 |
|
| listReleaseIterator | 释放迭代器 |
|
| listRewind | 将迭代器的指针指向表头 |
|
| listRewindTail | 将迭代器的指针指向表尾 |
|
| listNext | 取出迭代器当前指向的节点 |
|
Redis源码学习——双端链表,布布扣,bubuko.com
原文:http://blog.csdn.net/xsc_c/article/details/21242429