双向循环链表

1. 前言

双向循环链表,比单向链表多了一个方向,而且还是首尾相连的,所以双向循环链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。linux中双向循环链表定义在include/linux/list.h里。

2. 初始化

linux中list_head定义,可以看到这里没有存储数据等信息,只有next和prev指针,数据没有耦合在这里,只注重双向链表的实现。

struct list_head {
	struct list_head *next, *prev;
};

初始化宏定义,初始时都next和prev都指向head

#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
	struct list_head name = LIST_HEAD_INIT(name)

在这里插入图片描述

3. 插入节点

static inline void __list_add(struct list_head *new,
			      struct list_head *prev,
			      struct list_head *next)
{
	if (!__list_add_valid(new, prev, next))
		return;

	next->prev = new;
	new->next = next;
	new->prev = prev;
	WRITE_ONCE(prev->next, new);	//prev->next = new;
}

  • 这里是把new节点插入到prev和next之间,__list_add_valid进行有效性节点的判断,插入操作就是把相互指向的关系调整,把new的prev和next分别指向节点prev、next,next节点的prev指向new,prev节点的next指向new
  • WRITE_ONCE是linux中保证写入安全性的宏定义
static inline void list_add(struct list_head *new, struct list_head *head)
{
	__list_add(new, head, head->next);
}

static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
	__list_add(new, head->prev, head);
}
  • 假设初始时为Head和NodeA两个节点,如下图1,现在需要增加NodeB
  • list_add 加入方式如下图2所示,插入在Head和NodeA之间
  • list_add_tail 加入方式如下图2所示,插入到Head的最后面

在这里插入图片描述

4. 删除节点

static inline void __list_del(struct list_head * prev, struct list_head * next)
{
	next->prev = prev;
	WRITE_ONCE(prev->next, next);
}

static inline void __list_del_entry(struct list_head *entry)
{
	if (!__list_del_entry_valid(entry))
		return;

	__list_del(entry->prev, entry->next);
}

static inline void list_del(struct list_head *entry)
{
	__list_del_entry(entry);
	entry->next = LIST_POISON1;
	entry->prev = LIST_POISON2;
}
  • 删除即跳过这个节点,把前后节点连接起来,然后删除的节点要指向程序没有用的地址。

5. 为空判断

static inline int list_empty(const struct list_head *head)
{
	return READ_ONCE(head->next) == head;
}

6. 节点遍历

#define list_for_each(pos, head) \
	for (pos = (head)->next; pos != (head); pos = pos->next)

#define list_for_each_prev(pos, head) \
	for (pos = (head)->prev; pos != (head); pos = pos->prev)

7. 遍历节点所处的数据结构

当一个struct中是通过双向循环链表连接起来的,如何通过list_head遍历这个struct,如下面struct包含int数据和list_head。

typedef struct{
	int data;
	list_head *list_link;
}exp;

可先把结构转换为0地址上的数据结构,即可得到 list_link在struct中的偏移地址,用list_head减去偏移地址就是struct的起始地址。
ptr -> list_head节点
type -> 数据结构(如上即为exp)
member -> list_head在结构体中的名字(如上即list_link)

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

#define container_of(ptr, type, member) ({			\
	const typeof(((type *)0)->member) * __mptr = (ptr);	\
	(type *)((char *)__mptr - offsetof(type, member)); })
#define list_entry(ptr, type, member) \
	container_of(ptr, type, member)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值