在看《算法精解:C语言描述》的双链表chtbl和redis的双链表adlist.c发现代码思路基本是一致的。
但是,对于链表的初始化却不一样
1.《算法精解:C语言描述》风格
/*****************************************************************************
* *
* Define a structure for doubly-linked list elements. *
* *
*****************************************************************************/
typedef struct DListElmt_ {
void *data;
struct DListElmt_ *prev;
struct DListElmt_ *next;
} DListElmt;
/*****************************************************************************
* *
* Define a structure for doubly-linked lists. *
* *
*****************************************************************************/
typedef struct DList_ {
int size;
int (*match)(const void *key1, const void *key2);
void (*destroy)(void *data);
DListElmt *head;
DListElmt *tail;
} DList;
一开始定义结构体在栈上分配内存,后面传递结构体地址
int main(int argc, char **argv) {
DList list;
DListElmt *element;
int *data,
i;
/*****************************************************************************
* *
* Initialize the doubly-linked list. *
* *
*****************************************************************************/
dlist_init(&list, free);
init的时候传递结构体指针,直接赋值
void dlist_init(DList *list, void (*destroy)(void *data)) {
/*****************************************************************************
* *
* Initialize the list. *
* *
*****************************************************************************/
list->size = 0;
list->destroy = destroy;
list->head = NULL;
list->tail = NULL;
return;
}
2.Redis的风格
init的时候在堆上动态分配内存,返回结构体指针
/* 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;
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;
}
typedef struct listNode {
struct listNode *prev;
struct listNode *next;
void *value;
} listNode;
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;
说透一级指针和二级指以及(void**)&在双链表中的应用 [这里分析了双链表的删除]