内核版本:kernel 3.0.1 #include <stdio.h> #include <stdlib.h> #include <sys/queue.h> struct ElemType { int num; char *ptr; LIST_ENTRY(ElemType) entries; }; LIST_HEAD(List, ElemType); static struct List gListHead; // linux自带的LIST_END用不了,可能是要什么头文件,或者编译时候需要某个库支持,但是我暂时还没找到驾驭LIST_END的方法。 // (若有哪位大虾知道还请告知) // 下面是我自己模仿linux的LIST_END函数头写的。 struct ElemType* LIST_END(struct List *list) { struct ElemType *recv = NULL; struct ElemType *elem = NULL; LIST_FOREACH(elem, list, entries) { if (elem && elem->entries.le_next == NULL) { recv = elem; } } return recv; } // 尾部插入。linux没有提供(反正我没找到,若有哪位大虾知道还请告知)尾部插入的方法,只能自己实现了。 //void LIST_INSERT_TAIL(struct List *list, struct ElemType *elem, LIST_ENTRY name) // LIST_ENTRY不能通过编译,why? void LIST_INSERT_TAIL(struct List *list, struct ElemType *elem) { struct ElemType *tail = LIST_END(list); if (tail) { LIST_INSERT_AFTER(tail, elem, entries); } else { LIST_INSERT_HEAD(list, elem, entries); } } int main() { LIST_INIT(&gList); struct ElemType *elem1 = (struct ElemType *)malloc(sizeof(struct ElemType)); struct ElemType *elem2 = (struct ElemType *)malloc(sizeof(struct ElemType)); struct ElemType *elem3 = (struct ElemType *)malloc(sizeof(struct ElemType)); elem1->num = 11; elem2->num = 22; elem3->num = 33; // insert in the head LIST_INSERT_HEAD(&gList, elem1, entries); LIST_INSERT_HEAD(&gList, elem2, entries); LIST_INSERT_HEAD(&gList, elem3, entries); // insert in the tail //LIST_INSERT_TAIL(&gList, elem1); //LIST_INSERT_TAIL(&gList, elem2); //LIST_INSERT_TAIL(&gList, elem3); struct ElemType *elem; // 采用 for 循环遍历 for (elem = gList.lh_first; elem; elem = elem->entries.le_next) { printf("using for, num = %d\n", elem->num); if (elem->num == 22) { LIST_REMOVE(elem, entries); free(elem); //elem->num = 99; } } // 采用 LIST_FOREACH 遍历 LIST_FOREACH(elem, &gList, entries) { printf("using LIST_FOREACH, num = %d\n", elem->num); //if (elem->num == 33) { LIST_REMOVE(elem, entries); free(elem); } } LIST_FOREACH(elem, &gList, entries) { printf("using LIST_FOREACH, num = %d\n", elem->num); } return 0; }
linux 内核链表的应用
猜你喜欢
转载自blog.csdn.net/u011362297/article/details/49273139
今日推荐
周排行