熟悉内核链表的基本使用,主要是如下几个函数。
1.定义内核链表并初始化
struct list_head
{
struct list_head *prev; //前级指针
struct list_head *next;//后级指针
};
void INIT_LIST_HEAD(struct list_head *list)//初始化通用链表
{
//前后级指针都指向本身
list->next=list;
list->prev=list;
}
显示了内核链表的通用性和可移植性,内核链表中,没有数据域,纯指针域,用户使用内核链表,可以实现自己对数据域的封装定义。
2.如何把自己的数据域放入内核链表
把自己的数据域通过内核链表来维护的方式其实很简单,就是自己定义一个结构体,结构体成员里面加入内核链表即可,这里有个细节,为了避免动态内存的分配,因此决定成员里面不用链表指针的形式,比如实现如下封装
typedef struct Stu
{
struct list_head node;
char name[20];
int age;
int grade;
int NodeId;
}Stu;
3.链表增加函数
把自己的成员挂载到链表中,利用如下的方式,头插法和尾插法。
void list_add(struct list_head *node,struct list_head *head)//插入节点
{
node->next=head->next;
node->prev=head;
head->next->prev=node;
head->next=node;
}
void list_add_tail(struct list_head *node,struct list_head *head)//尾插
{
node->next=head->prev;
node->prev=head;
head->prev->next=node;
head->prev=node;
}
4.如何遍历链表
遍历链表使用如下宏函数:
/*遍历链表 依次为:从头节点的下一个节点开始遍历
* 从头节点的上一个节点开始遍历
*(以list_for_next_each为例理解:首先节点指针pos指向头节点的下一个节点,
判断 pos是否指向头节点,不是的话就向后继续遍历)
*/
#define list_for_next_each(pos,head)\
for(pos=(head)->next;pos!=(head);pos=pos->next)
#define list_for_prev_each(pos,head)\
for(pos=(head)->prev;pos!=(head);pos=pos->prev)
5.遍历完链表上的成员,需要将数据打印出来,遍历是通过链表的连接进行遍历,遍历后拿出链表对应的结构体方式如下
//提取数据结构 ptr 是链接因子的指针 type是包含了链接因子的数据类型 member是链接因子成员名
#define container_of(ptr,type,member)\
(type *)((int)ptr - (int)(&((type *)0)->member) )
组合起来就是
void Show(struct list_head *ClassList)
{
struct list_head *temp;
Stu *mytemp;
list_for_prev_each(temp,ClassList)
{
mytemp = container_of(temp,Stu,node);
printf("姓名:%s\n",mytemp->name);
}
}