//定义一个双向链表
struct listnode {
struct listnode *next;
struct listnode *prev;
};
//定位包含一个链表节点的结构体的首地址
#define node_to_item(node, container, member) \
(container *) (((char*) (node)) - offsetof(container, member))
//链表的声明
#define list_declare(name) \
struct listnode name = { \
.next = &name, \
.prev = &name, \
}
//正向遍历链表
#define list_for_each(node, list) \
for (node = (list)->next; node != (list); node = node->next)
//反向遍历链表
#define list_for_each_reverse(node, list) \
for (node = (list)->prev; node != (list); node = node->prev)
//正向遍历链表,同时定位两个链表节点
#define list_for_each_safe(node, n, list) \
for (node = (list)->next, n = node->next; \
node != (list); \
node = n, n = node->next)
//初始化一个链表
static inline void list_init(struct listnode *node)
{
node->next = node;
node->prev = node;
}
//在链表尾部添加一个新的节点
static inline void list_add_tail(struct listnode *head, struct listnode *item)
{
item->next = head;
item->prev = head->prev;
head->prev->next = item;
head->prev = item;
}
//在链表头部添加一个新的节点
static inline void list_add_head(struct listnode *head, struct listnode *item)
{
item->next = head->next;
item->prev = head;
head->next->prev = item;
head->next = item;
}
//移除链表中的某个节点
static inline void list_remove(struct listnode *item)
{
item->next->prev = item->prev;
item->prev->next = item->next;
}
//链表判空
#define list_empty(list) ((list) == (list)->next)
//头节点
#define list_head(list) ((list)->next)
//尾节点
#define list_tail(list) ((list)->prev)
linux内核中的链表实现: https://elixir.bootlin.com/linux/v5.7.2/source/include/linux/list.h