(1)声明list。
默认声明初始化是把链表的next和prev都指向自己。可以采用如下几个宏。
1.#define LIST_HEAD_INIT(name) { &(name), &(name) }
2.#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
3.static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
(2)加入一个list到链表里面,放到head的后面。
static inline void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->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 = new;
}
(3)加入一个list到链表(尾部),也即是放到head的前面。
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}
通过这行发现链表是非常方便和灵活的。Head->prev就是链表的尾部(环形链表),就是放到尾部后面。
(4)删除链表的节点(list)
static inline void list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
entry->next = LIST_POISON1;
entry->prev = LIST_POISON2;
}
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
next->prev = prev;
prev->next = next;
}
(5)判断list是否为空
static inline int list_empty(const struct list_head *head)
{
return head->next == head;
}