版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013139008/article/details/79638470
/* adlist.c - A generic doubly linked list implementation
*
* Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef _WIN32
#include "Win32_Interop/Win32_Portability.h"
#include "Win32_Interop/win32_types.h"
#endif
#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. */
list *listCreate(void)
{
struct list *list;
// 申请的内存的大小是sizeof(*list),不是sizeof(list),后者是指针大小
if ((list = zmalloc(sizeof(*list))) == NULL)
return NULL;
// 对list结构体的所有成员进行赋初值
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)
{
PORT_ULONG len;
listNode *current, *next;
current = list->head;
len = list->len;
while(len--) {
// 获得下一个结点
// 下一结点的指针需要提前保存,不然释放当前结点之后,就无法获得下一个结点
next = current->next;
// 释放当前结点的值,如果没有定义free函数,结点的值就不释放
if (list->free) list->free(current->value);
zfree(current); // 释放当前结点,因结点是由zmalloc申请的
current = next;
}
zfree(list); // 释放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;
// 通过判断len值,而不是判断list->head是否为空,这样更可靠?
if (list->len == 0) { // 该结点是list中的第一个结点
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++; // list的每一个字段都要判断是否需要改变
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_node前或者后插入一个结点node
*/
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) { // 插入old_node结点后面
node->prev = old_node;
node->next = old_node->next;
// 对old_node是否是最后一个结点进行判断,而不是执行下面操作:
//old_node->next->prev = node;
//old_node->next = node;
if (list->tail == old_node) {
list->tail = node;
//old_node->next = node; 无需该操作,下面判断node不是首尾结点的地方包含该操作
}
} else { // 插入old_node结点前面
node->next = old_node;
node->prev = old_node->prev;
// 对old_node是否是第一个结点进行判断,而不是执行下面操作:
//old_node->prev->next = node;
//old_node->prev = node;
if (list->head == old_node) {
list->head = node;
}
}
// 包含node处于中间结点的情况
if (node->prev != NULL) { // 如果node结点不是第一个结点,设置和node前一个结点的关系
node->prev->next = node;
}
if (node->next != NULL) { // 如果node结点不是最后一个结点,设置和node后一个结点的关系
node->next->prev = node;
}
list->len++;
return list; // 返回新的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. */
// 默认node结点一定是list中的结点
void listDelNode(list *list, listNode *node)
{
// 两个if-else操作,直接包含了四种情况
// 头结点、尾结点、中间结点、只有一个结点
if (node->prev) // 如果node不是第一个结点
node->prev->next = node->next;
else // 如果node是第一个结点,修改list结构体的头结点指针
list->head = node->next;
if (node->next) // 如果node不是最后一个结点
node->next->prev = node->prev;
else // 如果node是最后一个结点,修改list结构体的尾结点指针
list->tail = node->prev;
// 最后要释放value和结点
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. */
// 根据list返回一个迭代器
// 根据direction决定迭代顺序是list的头结点还是还是尾结点开始
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); // 释放迭代器占用的内存
}
// listRewind和listRewindTail函数的形参li,不知道函数调用之前迭代顺序是什么样的
// 但是知道调用这两个函数之后,迭代器的迭代顺序是什么样的
/* Create an iterator in the list private iterator structure */
// 迭代器修改为从前向后迭代
void listRewind(list *list, listIter *li) {
// 根据list修改迭代器结构体
li->next = list->head;
li->direction = AL_START_HEAD;
}
// 迭代器修改为从后向前迭代
void listRewindTail(list *list, listIter *li) {
// 根据list修改迭代器结构体
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;
/* 1.不能直接返回iter->next,需要保证下一次调用函数的正确性,
* 即需要进一步初始化iter中的字段
* 2.当前结点可能是迭代器的最后一个结点
* 如果不是最后一个结点才对迭代器的下一个结点进行新的赋值
*/
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;
// 根据orig列表创建一个迭代器,从头结点开始迭代
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 = 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. */
/* 考虑在一个函数中申请了哪些资源,在函数返回的时候是否要是否释放这些资源
* 防止资源泄露。如该函数中不要忘记调用函数listReleaseIterator
* 应该考虑到listGetIterator和listReleaseIterator成对调用
*/
listNode *listSearchKey(list *list, void *key)
{
listIter *iter;
listNode *node;
// 根据orig列表创建一个迭代器,从头结点开始迭代
iter = listGetIterator(list, AL_START_HEAD);
while((node = listNext(iter)) != NULL) {
if (list->match) { // 如果match函数存在,根据match函数的匹配规则进行匹配
// 如果node结点和key匹配成功,释放迭代器,返回匹配成功的结点
if (list->match(node->value, key)) {
listReleaseIterator(iter);
return node;
}
} else {
// 如果match函数不存在,则直接匹配key指针和value指针是否相同
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. */
/* 1.考虑index的正负可以指示不同的位置方向,函数的功能更健壮
* 2.函数中涉及到遍历列表的操作,但是没有使用迭代器,
* 因为函数中即有从前往后遍历,也有从后往前遍历,使用目前函数中的方法实现更简单。
*/
// 返回指定下标的结点指针
listNode *listIndex(list *list, PORT_LONG index) {
listNode *n;
// 从后往前数
if (index < 0) {
// 从后往前数,是从-1开始的,所以校正为正之后,再-1。
// 这样和从前开始数一样,从0开始计数
index = (-index)-1;
n = list->tail;
// 在对结点进行计数的同时,需要判断结点是否统计结束
// 如果统计到最后一个结点,但是index并不为0,就返回第一个结点
// 因为index=0是最后一个结点,所以使用index--,而不是--index
while(index-- && n) n = n->prev;
// 从前往后数
} else {
n = list->head;
// 如果统计到最后一个结点,但是index并不为0,就返回最后一个结点
while(index-- && n) n = n->next;
}
// 返回的结点不一定是和index相对应的结点,可能是第一个或最后一个结点
return n;
}
/* Rotate the list removing the tail node and inserting it to the head. */
// 将尾结点放在第一个结点
void listRotate(list *list) {
listNode *tail = list->tail;
// 如果结点数<=1,不需要执行该操作
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;
}
其他:
1.代码中涉及到结点中的void *value字段的操作,比如复制、释放、匹配操作,为了增加扩展性,使用可以指定的函数实现。没有指定特定函数的时候,使用简单的复制、释放、匹配操作。
2.对于一些简单的操作,如获得链表的长度,头结点,尾结点等操作,定义了宏函数实现,增加代码的封装和扩展性。
3.遍历链表的操作,通过使用迭代器的方式实现。
4.代码中注意资源的释放,如创建链表和释放链表的成对使用,创建迭代器和释放迭代器的成对使用