Linux kernel source code "two-way linked list list_head", linuxlist_head
Abstract: The linux kernel source code is really good, and is the crystallization of many experts. In the linux source code, the header file is list. h. Many linux source codes use this header file, which defines a structure and a group of functions related to it. The structure is as follows:
Structlist_head {
Structlist_head * next, * prev;
};
If you have learned a two-way linked list before, you may feel familiar when you see this structure. I have never been familiar with Fio. If you have read Fio source code, you will think it is so widely used. Here we will use an example to demonstrate how to use it.
I. write code
[Root @ bdkyr cstudy] # cat double_list.c
# Include <stdio. h>
# Include <stdlib. h>
# Include "list. h"
Struct int_node
{
/* Add as needed */
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); // initialize the linked list Header
List_add_tail (& a. list, & head); // Add a node
List_add_tail (& B. list, & head );
List_add_tail (& c. list, & head );
Printf ("************** print the result **************** \ n ");
List_for_each (plist, & head) // print the result in a recurring table.
{
Struct int_node * node = list_entry (plist, struct int_node, list); // then obtain the data item, so it is generally used with list_for_each.
Printf ("val = % d, num = % d \ n", node-> val, node-> num );
} // Print 1 1 2 2 3 3
Printf ("************* delete node B, repeat the link table, and print the result * \ n ");
List_del (& B. list); // delete node B
List_for_each (plist, & head) // repeat the Link Table and print the result.
{
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 the 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); // create a new linked list. The 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) // checks whether the linked list is empty.
{
Printf ("the list is not empty! \ N ");
}
Return 0;
}