一、前言
Linux内核链表作为内核最基础最常用的数据结构,那么在咱们用户态的编程下是否可以借鉴?
二、相关知识
1、双向循环链表
如图所示,每个节点分别有前驱(prev)、后继(next)两个指针域,双链表支持两个方向的遍历,循环则指尾节点又可以重新指向到头节点;
2、内核链表的实现(以3.10.25为例)
2.1 头节点定义(linux-3.10.25/include/linux/list.h)
struct list_head {
struct list_head *next, *prev;
}
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
首先是链表节点的实现与初始化,即头节点为空节点,并把前驱后继指向了自己;
然后仔细看这个头结构,会发现里头并未包含数据域,这里考虑的是要抽象出来与数据类型无关的链表接口;
2.2 节点增加删除
/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *node,
struct list_head *prev,
struct li