使用二级指针辅助遍历的单链表
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 阅读(66) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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框架的用法!