Abstract: Linux kernel source is really good stuff, is the crystallization of many master thinking, inLinuxA header file in the source code islist.h。 A lotLinuxUnder the source code will use this header file, it defines a structure,and defines a set of functions associated with it, this structure is:
structlist_head{
Structlist_head *next, *prev;
};
If you've learned about doubly linked lists before, you'll feel familiar when you see the structure. More than familiar, if you have seen Fio source code, you will feel it is used so widely, below we show through an example of how to use
First, write the code
[email protected] cstudy]# cat double_list.c
#include <stdio.h>
#include <stdlib.h>
#include "List.h"
struct Int_node
{
/ * Depending on the situation, increase * /
int Val;
int num;
/************/
struct List_head list;
};
int main ()
{
struct List_head head,*plist;
struct Int_node a,b,c;
A.val = 1;
A.num = 1;
B.val = 2;
B.num = 2;
C.val = 3;
C.num = 3;
Init_list_head (&head);//initialization of the chain header
List_add_tail (&a.list,&head);//Add node
List_add_tail (&b.list,&head);
List_add_tail (&c.list,&head);
printf ("************ traversal linked list, print results **************\n");
List_for_each (Plist,&head)//Traverse linked list, print results
{
struct Int_node *node = list_entry (plist,struct int_node,list);///Then get data item, so generally with List_for_each with
printf ("val =%d, num =%d\n", Node->val, Node->num);
}//print 1 1 2 2 3 3
printf ("************ Delete Node B, re-traverse linked list, print result *\n");
List_del (&b.list);//Remove Node B
List_for_each (Plist,&head)//re-traverse linked list, print results
{
struct Int_node *node = list_entry (plist,struct int_node,list);
printf ("val =%d, num =%d\n", Node->val, Node->num);
}//print 1 1 3 3
printf ("************ Print List head1******************\n");
struct Int_node d,e;
struct List_head head1;
D.val = 4;
D.num = 4;
E.val = 5;
E.num = 5;
Init_list_head (&HEAD1);//re-establish the linked list, the table header is Head1
List_add_tail (&D.LIST,&HEAD1);
List_add_tail (&E.LIST,&HEAD1);
List_for_each (PLIST,&HEAD1)
{
struct Int_node *node = list_entry (plist,struct int_node,list);
printf ("val =%d, num =%d\n", Node->val, Node->num);
}
printf ("*******************************************\n");
if (!list_empty (&head))//Determine if the linked list is empty
{
printf ("The list is not empty!\n");
}
return 0;
}
Linux kernel source "doubly linked list List_head"