/*******************************************************************************
*** Description: Simple doubly linked list implementation.
*******************************************************************************/
#ifndef __LIST_H__
#define __LIST_H__
/* 双向链表节点 */
typedef struct list_head
{
struct list_head *next;
struct list_head *prev;
} list_head_st;
/* 初始化节点 */
static inline void init_list_head(list_head_st *list)
{
list->next = list;
list->prev = list;
}
/* 添加节点: 将new插入到prev和next之间 */
static inline void __list_add(list_head_st *new, list_head_st *prev, list_head_st *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
/* 添加new节点: 将new添加到head之后 */
static inline void list_add(list_head_st *new, list_head_st *head)
{
__list_add(new, head, head->next);
}
/* 添加new节点: 将new添加到head之前, 即将new添加到双链表的末尾 */
static inline void list_add_tail(list_head_st *new, list_head_st *head)
{
__list_add(new, head->prev, head);
}
static inline void __list_del(list_head_st *prev, list_head_st *next)
{
next->prev = prev;
prev->next = next;
}
/* 从双链表中删除entry节点 */
static inline void list_del(list_head_st *entry)
{
__list_del(entry->prev, entry->next);
entry->next = NULL;
entry->prev = NULL;
}
/* 用new节点取代old节点 */
static inline void list_replace(list_head_st *old, list_head_st *new)
{
new->next = old->next;
new->next->prev = new;
new->prev = old->prev;
new->prev->next = new;
}
/* 双向链表是否为空 */
static inline int list_empty(const list_head_st *head)
{
return head->next == head;
}
/* 获取"MEMBER成员"在"结构体TYPE"中的位置偏移 */
#define OFFSET_OF(type, member) ((size_t) &((type *)0)->member)
/* 根据"结构体(type)变量"中的"域成员变量(member)的指针(ptr)"来获取指向整个结构体变量的指针 */
#define CONTAINER_OF(ptr, type, member) ({ \
const typeof(((type *)0)->member) *__mptr = (ptr); \
(type *)((char *)__mptr - OFFSET_OF(type, member));})
/* 遍历双向链表 */
#define LIST_FOR_EACH(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
#define LIST_FOR_EACH_SAFE(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); pos = n, n = pos->next)
/* 找出ptr指向的链表节点所在的type类型的结构体首地址 */
#define LIST_ENTRY(ptr, type, member) CONTAINER_OF(ptr, type, member)
#define LIST_FIRST_ENTRY(ptr, type, member) LIST_ENTRY((ptr)->next, type, member)
#endif
双向链表操作
于 2022-03-24 22:44:02 首次发布