Redis—數據結構之list

Redis的列表對象底層所使用的數據結構其中之一就是list。html

list

Redis的list是一個雙端鏈表,其由3部分構成:鏈表節點、鏈表迭代器、鏈表。這一設計思想和STL的list是同樣的,STL的list也是由這三部分組成。須要特別說明的是Redis用C語言實現了list的迭代器,比較巧妙,下面就來分析list源碼。node

list節點c++

節點的值爲void*類型,從而能夠保存不一樣類型的值,甚至是另外一種類型的對象redis

// 雙端鏈表的節點
typedef struct listNode {
    struct listNode *prev; // 指向上一個節點
    struct listNode *next; // 指向下一個節點
    void *value; // 指向節點的值, void*類型,使得節點能夠保存不一樣類型的值
} listNode;

list迭代器數據結構

c語言實現c++中的迭代器;雙端鏈表的迭代器,方便了遍歷鏈表的操做;根據direction,可設置爲前向/反向迭代器ide

typedef struct listIter {
    listNode *next;    // 指向迭代器方向上下一個鏈表結點
    int direction; // AL_START_HEAD=0:從頭部往尾部方向移動;AL_START_TAIL=1:往尾部往頭部方向移動
} listIter;

其中direction的取值有:函數

/* Directions for iterators */
// 迭代器方向的宏定義
#define AL_START_HEAD 0
#define AL_START_TAIL 1

listspa

與通常設計相似,list中有指向頭尾節點的指針,以及鏈表節點數量的計數。不一樣的是,因爲鏈表節點爲void*類型,被設計爲能夠存儲不一樣類型的數據,甚至是另外一種類型的對象,因此添加了與節點相關的3個函數,做用分別是複製、釋放、比較節點的值。設計

// 雙端鏈表
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;

 

list的操做函數

Redis用宏定義實現了一些複雜度爲O(1)的鏈表操做,以提升list操做的效率。指針

/* Functions implemented as macros */
// 經過宏來實現一些O(1)時間複雜度的函數
#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 listGetFree(l) ((l)->free)
#define listGetMatchMethod(l) ((l)->match)

 

list的源碼比較好理解,本人對其已經作了詳細的註釋,就不仔細介紹了,下面附上源碼及註釋。list相關的文件有兩個:adlist.h, adlist.c

adlist.h

#ifndef __ADLIST_H__
#define __ADLIST_H__

/* Node, List, and Iterator are the only data structures used currently. */

// redis的鏈表爲雙端鏈表
// 節點的值爲void*類型,從而能夠保存不一樣類型的值
// 結合dup,free,match函數實現鏈表的多態

// 雙端鏈表的節點
typedef struct listNode {
    struct listNode *prev; // 指向上一個節點
    struct listNode *next; // 指向下一個節點
    void *value; // 指向節點的值, void*類型,使得節點能夠保存不一樣類型的值
} listNode;

// c語言實現c++中的迭代器!!!
// 雙端鏈表的迭代器,方便了遍歷鏈表的操做
// 根據direction,可設置爲前向/反向迭代器
typedef struct listIter {
    listNode *next;    // 指向迭代器方向上下一個鏈表結點
    int direction; // AL_START_HEAD=0:從頭部往尾部方向移動;AL_START_TAIL=1:往尾部往頭部方向移動
} 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 */
// 經過宏來實現一些O(1)時間複雜度的函數
#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 listGetFree(l) ((l)->free)
#define listGetMatchMethod(l) ((l)->match)

/* Prototypes */
// list數據結構相關的函數
// 具體含義見adlist.c
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);
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 listRotate(list *list);

/* Directions for iterators */
// 迭代器方向的宏定義
#define AL_START_HEAD 0
#define AL_START_TAIL 1

#endif /* __ADLIST_H__ */
View Code

adlist.c

/* 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. */
 
// 建立一個鏈表
// 返回值:list/NULL
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); // 釋放鏈表節點的值
        zfree(current); // 釋放鏈表節點
        current = next;
    }
    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/NULL
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/NULL 
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;
}

// 在鏈表list的節點old_node的前或後插入新節點
// after爲0,則在old_node以前插入;不然,在old_node以後插入
// 返回值:list/NULL
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;
        if (list->tail == old_node) {
            list->tail = node;
        }
    } else { // old_node以前插入
        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. */

// 刪除鏈表list中節點node
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. */
 
 // 返回鏈表的迭代器
 // 返回值:list/NULL
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));
 * }
 *
 * */
 
 // 返回迭代器所指向的元素,並將迭代器往其方向上移動一步
 // 返回值:指向當前節點的指針/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. */
 
 // 複製輸入鏈表
 // list*/NULL
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;
    listRewind(orig, &iter); // 迴繞迭代器到鏈表頭部
    while((node = listNext(&iter)) != NULL) { // 遍歷原鏈表,順序取出節點
        void *value;

        if (copy->dup) {
            value = copy->dup(node->value); // 經過list.dup函數複製節點值
            if (value == NULL) {
                listRelease(copy); // 出錯釋放鏈表
                return NULL;
            }
        } else
            value = node->value;
        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. */
 
 // 返回鏈表中節點值與key相匹配的節點
 // listNode*/NULL
listNode *listSearchKey(list *list, void *key)
{
    listIter iter;
    listNode *node;

    listRewind(list, &iter);
    while((node = listNext(&iter)) != NULL) {
        if (list->match) {
            if (list->match(node->value, key)) { // 調用list.match函數對節點值進行比較
                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. */
 
 // 返回給定索引位置的節點
 // index=0,返回頭結點
 // index < 0,則從尾部開始返回,index = -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;
}
View Code

 

(全文完)

附:Redis系列:http://www.cnblogs.com/zxiner/p/7197415.html

相關文章
相關標籤/搜索