List of Linux Links: using a For loop to add a list, List_add, List_add_tail
Add 10 nodes to the linked list using a For loop
If you use List_add, the node is added to the list header, and then when you print with the subsequent list_for_each, it is inverted:
*********************************************
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
*********************************************
If you use List_add_tail, the nodes are added to the end of the chain, and when you print with the subsequent list_for_each, they are printed sequentially:
*********************************************
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
*********************************************
The source code is as follows:
[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_u Se_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;}
List of Linux Links: using a For loop to add a list, List_add, List_add_tail