使用for循环,向链表中添加10个节点
如果使用list_add,则将节点添加到链表头,那么使用后面的list_for_each打印时,便是倒着的:
*********************************************
index:9, name:name9
index:8, name:name8
index:7, name:name7
index:6, name:name6
index:5, name:name5
index:4, name:name4
index:3, name:name3
index:2, name:name2
index:1, name:name1
index:0, name:name0
*********************************************
如果使用list_add_tail,则将节点添加到链表尾,那么使用后面的list_for_each打印时,便是顺序打印的:
*********************************************
index:0, name:name0
index:1, name:name1
index:2, name:name2
index:3, name:name3
index:4, name:name4
index:5, name:name5
index:6, name:name6
index:7, name:name7
index:8, name:name8
index:9, name:name9
*********************************************
源码如下:
[email protected]:/mnt/shared/kernelbox/list# cat listuse.c #include "list.h" struct stListUse { char name[32]; int index; struct list_head list; }; LIST_HEAD(list_use_head); struct stListUse *pstListNode; int main(int argc, char *argv[]) { int i; char nametmp[32]; struct stListUse *pstListTmp; struct list_head *tmp; printf("enter listuse.c/main()\n"); for(i=0; i<10; i++) { pstListNode = (struct stListUse *)malloc(sizeof(struct stListUse)); memset(pstListNode, 0, sizeof(struct stListUse)); /* init node i */ pstListNode->index = i; sprintf(nametmp, "name%d", i); strcpy(pstListNode->name, nametmp); /* add node i to list list_use_head */ #if 0 list_add(&pstListNode->list, &list_use_head); #endif list_add_tail(&pstListNode->list, &list_use_head); } pstListTmp =(struct stListUse *)malloc(sizeof(struct stListUse)); /* print list */ printf("*********************************************\n"); list_for_each(tmp, &list_use_head) { pstListTmp = list_entry(tmp, struct stListUse, list); printf("index:%d, name:%s\n", pstListTmp->index, pstListTmp->name); } printf("*********************************************\n"); return 0; }
时间: 2024-10-05 04:58:51