A generic doubly linked list implementation
Redis的adlist.h和adlist.c共同定义了其基本数据结构list,其底层是一个带有迭代器的双向链表结构,迭代器的实现非常精巧。
adlist.h
#ifndef __ADLIST_H__
#define __ADLIST_H__
/* 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; // 迭代方向,用来选择prev还是next
} 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;
/* 获取链表基本信息的操作 */
#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 listGetFreeMethod(l) ((l)->free)
#define listGetMatchMethod(l) ((l)->match)
/* 函数原型,函数名含义清晰,基本实现了自注释 */
list *listCreate(void);
void listRelease(list *list);
void listEmpty(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 listRotateTailToHead(list *list);
void listRotateHeadToTail(list *list);
void listJoin(list *l, list *o);
/* Directions for iterators */
#define AL_START_HEAD 0 // 正向迭代方向,头--》尾
#define AL_START_TAIL 1 // 反向迭代方向,尾--》头
#endif /* __ADLIST_H__ */
adlist.c
#include <stdlib.h>
#include "adlist.h"
#include "zmalloc.h"
/* 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. */
list *listCreate(void)
{
struct list *list;
// 创建一个list对象,失败返回NULL
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;
}
/* Remove all the elements from the list without destroying the list itself. */
/* 释放链表,但不释放list对象的空间 */
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信息置初始值
list->head = list->tail = NULL;
list->len = 0;
}
/* Free the whole list.
*
* This function can't fail. */
/* 释放链表和list,释放空间,该函数不可能失败 */
void listRelease(list *list)
{
// 释放链表节点,list信息初始化
listEmpty(list);
// 释放list
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;
}
/* 在old_value的前面后者后面插入节点 */
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--;
}
/* 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
* pattern is:
*
* iter = listGetIterator(list,<direction>);
* while ((node = listNext(iter)) != NULL) {
* doSomethingWith(listNodeValue(node));
* }
*
* */
listNode *listNext(listIter *iter)
{
listNode *current = iter->next;
// 更新迭代器指向的节点,next根据迭代方向获取下一个,prev或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;
// 构造复制list的结构,失败返回NULL
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;
// 如果存在复制函数,则使用
if (copy->dup) {
value = copy->dup(node->value);
// 复制函数执行失败,返回NULL,整体复制不成功
if (value == NULL) {
listRelease(copy);
return NULL;
}
} else
value = node->value;
// 将复制的节点添加在复制list的尾部,如果添加失败,整体失败,返回NULL
if (listAddNodeTail(copy, value) == NULL) {
listRelease(copy);
return NULL;
}
}
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;
listRewind(list, &iter);
// 正向迭代器遍历所有节点,查找Key,如果有match函数,用match函数进行匹配
while((node = listNext(&iter)) != NULL) {
if (list->match) {
if (list->match(node->value, key)) {
return node;
}
} else {
if (key == node->value) {
return node;
}
}
}
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;
// 如果index < 0,则认为是反向迭代,从-1开始
if (index < 0) {
index = (-index)-1;
n = list->tail;
while(index-- && n) n = n->prev;
// 如果index > 0,则认为是正向迭代,从0开始
} 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 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. */
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. */
/* 将o的所有节点添加在l的尾部 */
void listJoin(list *l, list *o) {
if (o->head)
o->head->prev = l->tail;
// 如果l的长度非0
if (l->tail)
l->tail->next = o->head;
else
l->head = o->head;
// 如果o的长度非0
if (o->tail) l->tail = o->tail;
l->len += o->len;
/* Setup other as an empty list. */
o->head = o->tail = NULL;
o->len = 0;
}