双向链表的基本操作
定义一个双向链表,必须有一个头结点,一般用head表示。
定义head,其成员指针都指向自身。同时可以通过这个特性来判断链表是否为空,即仅有head,无其他结点存在。
双向链表结构体:
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)
通过LIST_HEAD(name)来定义和初始化双向链表。
//判断链表是否为空
//next指针指向自身则为空
static inline int list_empty(const struct list_head *head)
{
return head->next == head;
}
//向双向链表中添加一个节点
//前一个节点的next指向new
//后一个节点的prev指向new
//new的prev指向前一个节点
//new的next指向后一个节点
//即将前后两个结点拼接起来
static inline void __list_add(struct list_head *_new,
struct list_head *prev,
struct list_head *next)
{
next->prev = _new;
_new->next = next;
_new->prev = prev;
prev->next