例说Linux内核链表(三)

常用的linux内核双向链表API介绍

linux link list结构图如下:



内核双向链表的在linux内核中的位置:/include/linux/list.h

使用双向链表的过程,主要过程包括创建包含struct link_head结构的结构体(item),建立链表头,向链表中添加item(自定义数据结构,双向链表数据单元),删除链表节点,遍历链表,判空等。

1、建立自定义链表数据结构

  1. struct kool_list{  
  2.     int to;  
  3.     struct list_head list;  //包含链表头
  4.     int from;  
  5.     };//自定义欲链接的数据额结构,并包含双向链表结构  
2、建立链表头

  1.     struct kool_list mylist;  
  2.     INIT_LIST_HEAD(&mylist.list);//初始化一个链表表头  
  3.   
或者

static LIST_HEAD(adc_host_head);//初始化一个链表头adc_host_head

第二种创建链表头和第一种的区别在于,第二种在编译的时候才会被初始化。还有一点就是链表头是独立的还是位于自定义链表数据结构中的。就好比在《例说Linux内核链表(二)》中给出的链表结构图和本文给出的结构图的区别。

3、向链表添加item

list_add(struct list_head *new, struct list_head *head);

例如:

  1.  struct kool_list *tmp;  

  2.  tmp= (struct kool_list *)malloc(sizeof(struct kool_list));  
  3.           
  4.  printf("enter to and from:");  
  5.  scanf("%d %d", &tmp->to, &tmp->from);  //初始化数据结构
  6.         /* add the new item 'tmp' to the list of items in mylist */  
  7.  list_add(&(tmp->list), &(mylist.list));//项链表中添加新的元素节点,tmp中的list  

list_add_tail(struct list_head *new, struct list_head *head);

在链表的尾部添加一个item,和list_add的区别在于,list_add把新的item加到了链表头的后面,list_add_tail把item加到了链表头的前面。

4、遍历链表

list_for_each_entry(type *cursor, struct list_head *list, member)

这并不是一个函数,它是一个for循环,依次列出要遍历的链表,三个元素代表的意义:type *cursor代表item的指针,struct list_head *list是链表头,member是item中包含的list_head数据项。通过这三个数据可以定位到链表的每一个数据元素。其中定位原理就是结构体偏移。

例如:

  1.  list_for_each_entry(tmp, &mylist.list, list)  
  2.          printf("to= %d from= %d\n", tmp->to, tmp->from);  

这个宏可以分为两步,第一步是遍历链表,pos依次指向链表中每个item的struct list_head 结构,第二步是获取pos指向的struct list_head所在的item。这里是tmp 。

list_for_each(pos, &mylist.list){//遍历链表,pos依次指向链表的元素

tmp= list_entry(pos, struct kool_list, list);//获得包含pos节点的数据结构指针    

5、删除

删除链表中的某节点,首先要使用安全遍历,然后再删除。

例如:

  

  1. list_for_each_safe(pos, q, &mylist.list){  
  2.          tmp= list_entry(pos, struct kool_list, list);  
  3.          printf("freeing item to= %d from= %d\n", tmp->to, tmp->from);  
  4.          list_del(pos);  

6、链表空

int list_empty(struct list_head *head);

Returns a nonzero value if the given list is empty.


参考网站:http://www.makelinux.net/ldd3/chp-11-sect-5 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值