Linux里面链表使用非常频繁,下面来看看Linux是怎么玩链表的。下面代码均取自/include/linux/list.h
一 Linux链表定义
struct list_head {
struct list_head *next, *prev;
};
Linux对链表抽象了一个最小的单位list_head,它只有两个成员:next指向后一个节点,pre指向前一个节点。
二 链表操作
1. 链表初始化
把pre和next都指向自身!判断链表是否为空即判断xxx->next = xxx 是否为true。
#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;
}
Linux里面链表的初始化提供了两种方式,1-4行使用宏的方式实现,将3-4行展开实际上就等于:
struct list_head name = {&(name), &(name)} // 即name->pre = name, name->next = name
6-10行采用内联函数直接赋值的方式。
2. 添加元素
Linux链表是双向链表,我们可以从其