双向链表的实现


//定义一个双向链表
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值