从基本数据结构入手分析。首先是双向链表的实现adlist.c,借此复习链表的基本操作。分析工程中感受最深的就是函数指针的大量使用,由于很长时间没有用C,这一块正是需要熟悉的。 除此之外,见识了在C语言中迭代器的实现原来可以很简洁。
下面是adlist.h与adlist.c,具体分析见注释。
adlist.h:
<span style="font-size:18px;">/* adlist.h - A generic doubly linked list implementation
#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;
} 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;
/* Functions implemented as macros */
//宏定义一些基本操作
#define listLength(l) ((l)->len) //取list长度
#define listFirst(l) ((l)->head) //取list头结点
#define listLast(l) ((l)->tail)//取list尾节点
#define listPrevNode(n) ((n)->prev)//取当前节点的prev节点
#define listNextNode(n) ((n)->next)//取当前节点的next节点
#define listNodeValue(n) ((n)->value)//取当前节点的value指针
#define listSetDupMethod(l,m) ((l)->dup = (m)) //设置list的复制方法
#define listSetFreeMethod(l,m) ((l)->free = (m))//设置list的释放方法
#define listSetMatchMethod(l,m) ((l)->match = (m))//设置list的匹配方法
#define listGetDupMethod(l) ((l)->dup) //取list的复制方法
#define listGetFree(l) ((l)->free) // 取list的释放方法
#define listGetMatchMethod(l) ((l)->match)//取list的匹配方法
/* 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);//迭代器指向next
void listReleaseIterator(listIter *iter);//释放迭代器
list *listDup(list *orig);//复制链表
listNode *listSearchKey(list *list, void *key);//查找key对应的节点
listNode *listIndex(list *list, long index);//查找索引index对应的节点
void listRewind(list *list, listIter *li);//重置迭代器方向为从头开始
void listRewindTail(list *list, listIter *li);//重置迭代器方向为从尾部开始
void listRotate(list *list);//链表循环右移操作
/* Directions for iterators */
//迭代器方向
#define AL_START_HEAD 0 //0为从头开始 前向
#define AL_START_TAIL 1 //1为从尾部开始 后向
#endif /* __ADLIST_H__ */
</span>
<span style="font-size:18px;"></span>
adlist.c :
<span style="font-size:18px;">/* adlist.c - A generic doubly linked list implementation
*/
#include <stdlib.h>
#include "adlist.h"
#include "zmalloc.h"
/* 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. */
//创建一个链表,可用函数AlFreeList()来释放整个链表,但是每个节点的私有值需要在调用函数AlFreeList()之前由调用者自己释放
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);//释放当前节点的value指针指向的内容
zfree(current); //释放当前节点
current = next;
}
zfree(list); //释放链表结构体
}
/* Add a new node to the list, to head, contaning 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. */
//在头部添加一个新节点,添加失败则返回null,原链表不改变,成功则返回返回传入的list*指针
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. */
//添加一个新节点到尾部,失败则返回null,原链表保持不变,成功则返回传入的list*指针
list *listAddNodeTail(list *list, void *value)
{
listNode *node;
if ((node = zmalloc(sizeof(*node))) == NULL)//为新节点分配空间
return NULL; //失败则返回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) { //after为非零值,则在插入到其后
node->prev = old_node;
node->next = old_node->next;
if (list->tail == old_node) { //如果old_node为尾节点,则需要更新尾指针
list->tail = node;
}
} else { //插入到其前
node->next = old_node;
node->prev = old_node->prev;
if (list->head == old_node) { //如果old_node为头节点,则需要更新头指针
list->head = node;
}
}
if (node->prev != NULL) {//更新old_node的next
node->prev->next = node;
}
if (node->next != NULL) {//更新old_node的prev
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. */
//获取链表的迭代器,迭代器初始化后,listNext()函数就返回链表的next节点。 以指定方向遍历链表
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));
* }
*
* */
//返回迭代器的next节点的指针(注意与迭代器的方向有关!),由于返回的是指针,因此可用于删除链表中的节点。
//如果没有next节点,则返回null,
//注意典型应用::获取当前节点的迭代器,在获取其next节点指针,并判断返回值是否为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;
}
/* 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,成功则返回原链表的拷贝。 listSetDupMethod()设置的Dup方法用于拷贝节点的value值,
//拷贝将共用原链表的节点值,即拷贝的节点指针指向原来的节点
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) {//如果设置了dup函数指针,则复制拷贝
value = copy->dup(node->value);
if (value == NULL) {//拷贝节点失败
listRelease(copy);
listReleaseIterator(iter);
return NULL;
}
} else//没有设置dup函数指针,则直接返回原节点value指针,即拷贝链表与原链表的value值指向同一值
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. */
//从头部开始查找与给定key匹配的第一个节点。匹配时使用设置的match方法把key与直接比较每个节点的value。
//找到则返回节点指针,失败则返回null
listNode *listSearchKey(list *list, void *key)
{
listIter *iter;
listNode *node;
iter = listGetIterator(list, AL_START_HEAD);
while((node = listNext(iter)) != NULL) {
if (list->match) {//如果设置了match函数指针
if (list->match(node->value, key)) {
listReleaseIterator(iter);
return node;
}
} else {
if (key == node->value) {//没有设置match函数指针,则用 == 来匹配
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. */
//查找指定索引的节点。 头结点索引为0,逐渐递增。 -1为尾节点,向前递减
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;
}
</span>