Home Database Mysql Tutorial 【Redis】对通用双向链表实现的理解

【Redis】对通用双向链表实现的理解

Jun 07, 2016 pm 03:54 PM
redis accomplish understand Universal linked list

Redis实现的双向链表还是比较容易看得懂的,其实现的原理很经典, 代码很整洁清晰。 以下是对其源码注释的翻译及本人见解的部分说明,如有偏颇欢迎指正: /* adlist.h - 通用双向链表的实现*/#ifndef __ADLIST_H__#define __ADLIST_H__/* 目前的数据结构只使用

Redis实现的双向链表还是比较容易看得懂的,其实现的原理很经典, 代码很整洁清晰。

以下是对其源码注释的翻译及本人见解的部分说明,如有偏颇欢迎指正:

/* adlist.h - 通用双向链表的实现*/

#ifndef __ADLIST_H__
#define __ADLIST_H__

/* 目前的数据结构只使用了Node, List, and Iterator. */

/* list节点*/
typedef struct listNode {
    struct listNode *prev;        // 前向指针
    struct listNode *next;        // 后向指针
    void *value;                  // 当前节点值
} listNode;

/* list迭代器*/
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;

/* 函数宏定义 */
#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 *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);                                       // 给定key查找节点
listNode *listIndex(list *list, long index);                                          // 给定index查找节点
void listRewind(list *list, listIter *li);                                            // 迭代器指针重新指向头节点
void listRewindTail(list *list, listIter *li);                                        // 迭代器指针重新指向末节点
void listRotate(list *list);                                                          // 链表翻转, 末节点移动成为头节点

/* 迭代器的迭代方向 */
#define AL_START_HEAD 0
#define AL_START_TAIL 1

#endif /* __ADLIST_H__ */
Copy after login
/* adlist.c - 通用双向链表的实现 */

#include <stdlib.h>
#include "adlist.h"
#include "zmalloc.h"

/* 创建新链表. 新建的链表可以用函数
* AlFreeList()来释放, 但调用此函数之前需要要应用手动释放对每个节点的私有值空间
*
* 出现错误则返回NULL,否则返回指向该list的指针*/
list *listCreate(void)
{
    struct list *list;

    if ((list = zmalloc(sizeof(*list))) == NULL)       // 用了在malloc之上封装的zmalloc来申请内存
        return NULL;
    list->head = list->tail = NULL;
    list->len = 0;
    list->dup = NULL;
    list->free = NULL;
    list->match = NULL;
    return list;
}

/* 释放链表,该方法不能失败.
*
 */
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);       // zfree基于系统函数free上的封装                                
        current = next;
    }
    zfree(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;
}

/* 把包含指针指向的值的节点插入链表尾部,

* 如发生错误,将返回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;
}

/* 把新节点插入链表某个节点的前或后,
* 如发生错误,将返回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) {                          // after!=0则表示节点插入的位置在旧节点之后,否则在其之前
        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;
}

/* 从链表中删除某个节点.
* 会调用底层函数把节点的空间释放.
*
* 该方法不能失败. */
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--;
}

/* 获取迭代器对象&#39;iter&#39;. 在初始化之后
*每次调用listNext()都会返回链表的下一个元素.
*
* 该方法不能失败. */
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;
}

/* 释放迭代器对象的空间 */
void listReleaseIterator(listIter *iter) {
    zfree(iter);
}

/* 将迭代器指针重新指向表头 */
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;
}

/* 获取迭代器的下一个元素.
* 可以通过listDelNode()方法来删除当前返回的节点,但不能删除其他的节点。
*
* 如果成功则返回迭代器的下一个元素,否则返回NULL;
* 因此推荐以下这样使用:
*
* iter = listGetIterator(list,<direction>);
* while ((node = listNext(iter)) != NULL) {
* doSomethingWith(listNodeValue(node));
* }
*
* */
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;
}

/* 复制整个链表. 
* 成功则返回复制的链表指针,否则返回NULL.
*
* 复制的方法通过listSetDupMethod()来指定,
* 如果没有指定dup方法则会完整拷贝原始节点的值.
*
* 原始链表不会给更改. */
list *listDup(list *orig)       // 有个疑问: 既然需要保持原始链表的不被修改,为什么不加const修饰?
{
    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) {
            value = copy->dup(node->value);
            if (value == NULL) {
                listRelease(copy);
                listReleaseIterator(iter);
                return NULL;
            }
        } else
            value = node->value;
        if (listAddNodeTail(copy, value) == NULL) {
            listRelease(copy);
            listReleaseIterator(iter);
            return NULL;
        }
    }

    listReleaseIterator(iter);

    return copy;
}

/* 通过指定key来查找节点.
* 查找节点的匹配方法可以通过listSetMatchMethod()来指定. 
* 如果外部调用模块没有指定匹配方法, 则直接比较key值和链表中节点指针指向的值.
*
* 如果正常将返回第一个匹配的节点指针,如果找不到匹配元素则返回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) {
                listReleaseIterator(iter);
                return node;
            }
        }
    }
    listReleaseIterator(iter);   // 释放iter对象
    return NULL;
}

/* 根据index来获取元素。
* 如果传入index为非负值,说明为正向迭代: 0为头节点,1为下一个节点,以此类推.
* 如果为负值,则说明为反向迭代: -1为尾节点, -2为倒数第二个节点, 以此类推
* 如果index越界则返回NULL. */
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;
}

/* 翻转链表, 将尾节点插入到链表头. */
void listRotate(list *list) {
    listNode *tail = list->tail;

    if (listLength(list) <= 1) return;

    /* 将当前末节点从链表中摘除 */
    list->tail = tail->prev;
    list->tail->next = NULL;
    /* 将末节点插入链表头 */
    list->head->prev = tail;
    tail->prev = NULL;
    tail->next = list->head;
    list->head = tail;
}
Copy after login
有两点还需要继续了解:

1)既然源码中list空间的创建及销毁是通过zmalloc模块的zmalloc和zfree来完成, zmalloc又是怎么实现的呢?

2)很好奇这么多对象指针都没有const作为限制, 是什么原因可以省略了它呢?

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 May 08, 2024 pm 03:50 PM

1. Start the [Start] menu, enter [cmd], right-click [Command Prompt], and select Run as [Administrator]. 2. Enter the following commands in sequence (copy and paste carefully): SCconfigwuauservstart=auto, press Enter SCconfigbitsstart=auto, press Enter SCconfigcryptsvcstart=auto, press Enter SCconfigtrustedinstallerstart=auto, press Enter SCconfigwuauservtype=share, press Enter netstopwuauserv , press enter netstopcryptS

Golang API caching strategy and optimization Golang API caching strategy and optimization May 07, 2024 pm 02:12 PM

The caching strategy in GolangAPI can improve performance and reduce server load. Commonly used strategies are: LRU, LFU, FIFO and TTL. Optimization techniques include selecting appropriate cache storage, hierarchical caching, invalidation management, and monitoring and tuning. In the practical case, the LRU cache is used to optimize the API for obtaining user information from the database. The data can be quickly retrieved from the cache. Otherwise, the cache can be updated after obtaining it from the database.

Caching mechanism and application practice in PHP development Caching mechanism and application practice in PHP development May 09, 2024 pm 01:30 PM

In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 May 08, 2024 pm 05:10 PM

First you need to set the system language to Simplified Chinese display and restart. Of course, if you have changed the display language to Simplified Chinese before, you can just skip this step. Next, start operating the registry, regedit.exe, directly navigate to HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlNlsLanguage in the left navigation bar or the upper address bar, and then modify the InstallLanguage key value and Default key value to 0804 (if you want to change it to English en-us, you need First set the system display language to en-us, restart the system and then change everything to 0409) You must restart the system at this point.

How to use Redis cache in PHP array pagination? How to use Redis cache in PHP array pagination? May 01, 2024 am 10:48 AM

Using Redis cache can greatly optimize the performance of PHP array paging. This can be achieved through the following steps: Install the Redis client. Connect to the Redis server. Create cache data and store each page of data into a Redis hash with the key "page:{page_number}". Get data from cache and avoid expensive operations on large arrays.

How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 May 08, 2024 am 10:34 AM

1. First, double-click the [This PC] icon on the desktop to open it. 2. Then double-click the left mouse button to enter [C drive]. System files will generally be automatically stored in C drive. 3. Then find the [windows] folder in the C drive and double-click to enter. 4. After entering the [windows] folder, find the [SoftwareDistribution] folder. 5. After entering, find the [download] folder, which contains all win11 download and update files. 6. If we want to delete these files, just delete them directly in this folder.

PHP Redis caching applications and best practices PHP Redis caching applications and best practices May 04, 2024 am 08:33 AM

Redis is a high-performance key-value cache. The PHPRedis extension provides an API to interact with the Redis server. Use the following steps to connect to Redis, store and retrieve data: Connect: Use the Redis classes to connect to the server. Storage: Use the set method to set key-value pairs. Retrieval: Use the get method to obtain the value of the key.

Comparison of algorithm time complexity of PHP arrays and linked lists Comparison of algorithm time complexity of PHP arrays and linked lists May 07, 2024 pm 01:54 PM

Comparison of the algorithm time complexity of arrays and linked lists: accessing arrays O(1), linked lists O(n); inserting arrays O(1), linked lists O(1)/O(n); deleting arrays O(1), linked lists O(n) (n); Search array O(n), linked list O(n).

See all articles