使用二级指针辅助遍历的单链表

1. 代码

复制代码
#include <stdio.h>
#include <stddef.h>

struct notifier_block {
    struct notifier_block *next;
    int priority;
};

struct notifier_block *head = NULL;

static int notifier_chain_register(struct notifier_block **nl, struct notifier_block *n)
{
    while (*nl != NULL) {
        if (*nl == n) {
            printf("double register detected\n");
            return 0;
        }
        if (n->priority > (*nl)->priority)
            break;
        nl = &((*nl)->next);
    }
    n->next = *nl;
    *nl = n;
    return 0;
}

static int notifier_chain_unregister(struct notifier_block **nl, struct notifier_block *n)
{
    while (*nl != NULL) {
        if (*nl == n) {
            *nl = n->next;
            return 0;
        }
        nl = &(*nl)->next;
    }
    return -1;
}

static void notifier_chain_print(struct notifier_block **nl)
{
    while (*nl != NULL) {
        printf("priority=%d\n", (*nl)->priority);
        nl = &(*nl)->next; 
    }
    
    
    
}

int main()
{
    int i;

    struct notifier_block b1 = {.priority = 1,};
    struct notifier_block b2 = {.priority = 4,};    
    struct notifier_block b3 = {.priority = 7,};
    struct notifier_block b4 = {.priority = 2,};
    struct notifier_block b5 = {.priority = 5,};
    struct notifier_block b6 = {.priority = 8,};

    struct notifier_block *pb[] = {&b1, &b2, &b3, &b4, &b5, &b6};

    for(i = 0; i < 6; i++) {
        notifier_chain_register(&head, pb[i]);
    }
    notifier_chain_print(&head); /*8 7 5 4 2 1*/

    notifier_chain_unregister(&head, &b4);
    notifier_chain_unregister(&head, &b5);
    notifier_chain_print(&head); /*8 7 4 1*/
}
复制代码

参考5.10内核中的同名函数实现。之后head是直接指向,其它成员之间都是通过next成员指向。优点是可以省去head这个节点。缺点不好理解。

 

posted on   Hello-World3  阅读(66)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示