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

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 2021-12-13 13:07  Hello-World3  阅读(65)  评论(0编辑  收藏  举报

导航