Linux 内核双向链表 list_head

举个栗子

struct student { // 学生
    int id; // 学号
    int score; // 分数
    struct student *next, *prev;
}

struct student 可以表示一个学生的链表(将一个个学生链起来),成员变量 *next、*prev 可以表示前和后的指针

一、双向链表 list_head

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

问题 1:list_head 既然是双向链表,链接的数据是什么,在哪里?

struct student 有一个分别指向前后的指针
struct list_head 有一个分别指向前后的指针
使用 struct list_head list; 替换 struct student *next, *prev;

struct student { // 学生
    int id; // 学号
    int score; // 分数
    struct list_head list;
}

问题 2:真的能用 struct list_head 替换 struct student 吗?
解:list_head 作为 student 的成员,通过 list_head 的地址可以获得 student 的地址(关键就是 list_entry 宏)

1.1 宏 list_entry

/**
 * list_entry - 获取给定 list_head 成员的宿主结构 entry
 * @ptr:	类型是 struct list_head(指向成员 member 的指针)
 * @type:	宿主容器结构的类型
 * @member:	内部的 list_head 的变量名字(成员 member 的名称),类型是 struct list_head
 */
#define list_entry(ptr, type, member) \
	container_of(ptr, type, member)

1.2 宏 container_of

/**
 * container_of - 将成员 member 的地址强制转换为该包含该成员 member 的结构的地址,即实现上面 "问题 2" 的功能
 * @ptr:	指向成员 member 的指针
 * @type:	成员 member 所嵌入的宿主容器结构的类型
 * @member:	结构中成员 member 的名称
 */
#define container_of(ptr, type, member) ({			\
    const typeof(((type *)0)->member) * __mptr = (ptr);	\
    (type *)((char *)__mptr - offsetof(type, member)); })

先看第一行代码

(type *)((char *)__mptr - offsetof(type, member));

第一行代码的作用是获取结构体 member 的地址(通过 member 的地址可以算出包含该成员 member 的结构的地址)

问:ptr 的注释是:the pointer to the member,为什么还要转为 member 类型的 __mptr?
答:使用 __mptr 的目的是在编译期间进行类型检测(第一句,赋值时如果类型不匹配会报告警),保证传入的成员地址与成员类型是匹配的,而在运行期间则和忽略中间变量 __mptr 是一样的

第二行代码

(type *)((char *)__mptr - offsetof(type, member));

1.3 宏 offsetof(type, member)

还是一个宏,解释一下 offsetof(type, member) 的含义

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
  • (TYPE *)0
    把 0 地址转(结构体起始地址)为 TYPE 指针
  • &((TYPE *)0)->MEMBE
    优先级:& 小于 ->,获取 TYPE 的 MEMBER 的地址
  • (size_t) &((TYPE *)0)->MEMBER
    将 MEMBER 的地址强制转为 size_t(int)型

offsetof 的作用是获取 MEMBER 在 TYPE 中的偏移量

offsetof 获取 MEMBER 在 TYPE 中的偏移量

再次看一下第二行代码

(type *)((char *)__mptr - offsetof(type, member));
  • (char )__mptr
    这里要将结构体 member 的地址转为 char
    类型,原因是指针在计算偏移,非指针加减(加减移动 4 字节),内存的最小单位是字节,转为 char* 符合要求
  • offsetof(type, member)
    MEMBER 在 TYPE 中的偏移量
  • (type *)((char )__mptr - offsetof(type, member))
    (type
    )(结构体 member 的地址 - MEMBER 在 TYPE 中的偏移量) = 包含成员 member 的结构的地址

第二行代码的作用是获取包含 member 的那个含有真实数据的结构体的地址,即通过指向结构体成员 member 的指针 ptr 获取指向整个结构体的指针

通过指向结构体成员 member 的指针 ptr 获取指向整个结构体的指针

二、相关操作

2.1 声明和初始化链表

// 仅初始化:将 name 的地址直接分别赋值给 next 和 prev,都指向自己
#define LIST_HEAD_INIT(name) { &(name), &(name) }

// 声明并初始化:定义链表头 name(头结不使用,不带有效数据),通过 LIST_HEAD_INIT 初始化双向循环链表
#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

list_head 默认为空链表(前后指针都初始化为指向自己)

2.2 链表判空

函数前关键字 static:静态函数,限制函数作用域(static 函数作用域仅限本文件),具有信息隐藏的作用
函数前关键字 inline:对编译程序可见,即编译程序在调用函数时会立即展开函数

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

2.3 添加元素

// 头插(相当于栈)
static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next); // 把新项 new 添加到 head 之后
}

// 尾插(相当于队列)
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
    __list_add(new, head->prev, head); // 把新项 new 添加到 head 之前
}

通用插入函数:__list_add(下划线开始的函数用于内部调用)

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;
}

list_add:
list_add

list_add_tail:
list_add_tail

2.4 删除元素

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_init(struct list_head *entry)
{
    __list_del_entry(entry);
    INIT_LIST_HEAD(entry);
}

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

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

通用删除函数:__list_del(下划线开始的函数用于内部调用)

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

list_del 和 list_del_init:
list_del 和 list_del_init

2.5 修改元素

static inline void list_replace(struct list_head *old, struct list_head *new)
{
    new->next = old->next;
    new->next->prev = new;
    new->prev = old->prev;
    new->prev->next = new;
}

static inline void list_replace_init(struct list_head *old, struct list_head *new)
{
    list_replace(old, new);
    INIT_LIST_HEAD(old);
}

list_replace 和 list_replace_init

2.6 遍历元素

list_for_each、list_for_each_safe:获取节点 pos 在链表中的偏移位置

// pos:指向宿主结构的指针(如:student)
// head:进行遍历的链表头指针
#define list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next)

// list_for_each:若当前 pos 指向的元素被删除,pos 的指向就会改变,就无法再通过 pos->next 指向链表的后续元素,可以选择安全的 list_for_each_safe

// safe 体现在哪?
// 这里的 pos 和 n 关系为:n = pos->next,若当前 pos 指向的元素被删除,pos 的指向就会改变,但此时依然可以通过 n 标识被删元素的下一个元素
#define list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); \
        pos = n, n = pos->next)

list_for_each_entry:遍历给定类型的列表

// pos:指向宿主结构的指针(如:student)
// head:进行遍历的链表头指针
// member:list_head 成员在宿主结构中的名字
#define list_for_each_entry(pos, head, member)				\
    for (pos = list_entry((head)->next, typeof(*pos), member);	\
        &pos->member != (head); 	\
        pos = list_entry(pos->member.next, typeof(*pos), member))

list_entry,在上面 1.1 处已经解释过

/**
 * list_entry - 获取给定 list_head 成员的宿主结构 entry
 * @ptr:	类型是 struct list_head(指向成员 member 的指针)
 * @type:	宿主容器结构的类型
 * @member:	内部的 list_head 的变量名字(成员 member 的名称),类型是 struct list_head
 */
#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

回顾 list_entry 结论:通过指向结构体成员 member 的指针 ptr 获取指向整个结构体的指针(如:根据一个结构体变量中的一个域成员变量 list_head 的指针来获取宿主容器结构 student 的指针)

三、使用方式

在 C++ 中使用 Linux 内核双向链表 list_head

3.1 my_list.h(参照 Linux 的 list.h 代码)

#ifndef _LINUX_LIST_H
#define _LINUX_LIST_H

#include <iostream>
#include <time.h>

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

#define container_of(ptr, type, member) \
    ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

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

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

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

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

/**
 * list_add - add a new entry
 * @new: new entry to be added
 * @head: list head to add it after
 *
 * Insert a new entry after the specified head.
 * This is good for implementing stacks.
 */
static inline void list_add(struct list_head *new_obj, struct list_head *head)
{
    __list_add(new_obj, head, head->next);
}

/**
 * list_for_each	-	iterate over a list
 * @pos:	the &struct list_head to use as a loop cursor.
 * @head:	the head for your list.
 */
#define list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next)

/**
 * list_entry - get the struct for this entry
 * @ptr:	the &struct list_head pointer.
 * @type:	the type of the struct this is embedded in.
 * @member:	the name of the list_struct within the struct.
 */
#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

/**
 * list_for_each_entry	-	iterate over list of given type
 * @pos:	the type * to use as a loop cursor.
 * @head:	the head for your list.
 * @member:	the name of the list_struct within the struct.
 */
// list_entry 第二个参数这里写死了 struct student(本来是 typeof(*pos))暂时不知道怎么动态传类型
#define list_for_each_entry(pos, head, member)				\
    for (pos = list_entry((head)->next, struct student, member);	\
        &pos->member != (head); 	\
        pos = list_entry(pos->member.next, struct student, member))

/**
 * list_for_each_entry_reverse - iterate backwards over list of given type.
 * @pos:	the type * to use as a loop cursor.
 * @head:	the head for your list.
 * @member:	the name of the list_struct within the struct.
 */
// list_entry 第二个参数这里写死了 struct student(本来是 typeof(*pos))暂时不知道怎么动态传类型
#define list_for_each_entry_reverse(pos, head, member)			\
    for (pos = list_entry((head)->prev, struct student, member);	\
        &pos->member != (head); 	\
        pos = list_entry(pos->member.prev, struct student, member))

/**
 * list_for_each_safe - iterate over a list safe against removal of list entry
 * @pos:	the &struct list_head to use as a loop cursor.
 * @n:		another &struct list_head to use as temporary storage
 * @head:	the head for your list.
 */
#define list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); \
        pos = n, n = pos->next)

/**
 * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
 * @pos:	the type * to use as a loop cursor.
 * @n:		another type * to use as temporary storage
 * @head:	the head for your list.
 * @member:	the name of the list_struct within the struct.
 */
#define list_for_each_entry_safe(pos, n, head, member)			\
    for (pos = list_entry((head)->next, struct student, member),	\
        n = list_entry(pos->member.next, struct student, member);	\
        &pos->member != (head); 					\
        pos = n, n = list_entry(n->member.next, struct student, member))

/*
 * Delete a list entry by making the prev/next entries
 * point to each other.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
	next->prev = prev;
	prev->next = next;
}

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

/**
 * list_empty - tests whether a list is empty
 * @head: the list to test.
 */
static inline int list_empty(const struct list_head *head)
{
	return head->next == head;
}

#endif

3.2 main.cpp

// List.cpp: 定义应用程序的入口点。
//

#include "my_list.h"

#define random() (rand() % (100 - 60 + 1)+ 60) // 随机数生成范围:[60, 100]

using namespace std;

struct student
{
	// 数据域
    int id; // 学号
    int score; // 分数
	
	// 指针域
    struct list_head list;
};

int main()
{
	// 根据运行程序的时间产生不同的随机数种子
	srand((unsigned)time(NULL));
	
	// 声明并初始化链表:链表头不使用(指针域 stu_first.list 对应的 stu_first 的数据域不是有效数据),只给链表头起名为 stu_head
    // 内部通过 LIST_HEAD_INIT 初始化双向循环链表,链表头 stu_head 的前后指针都指向链表头 stu_head 自己
    LIST_HEAD(stu_head);

    // 添加元素
    int i;
    struct student *stu;
    for (i = 0; i < 5; i++)
    {
        stu = (struct student*)malloc(sizeof(student));
        stu->id = i + 1;
        stu->score = random();
        
        // 添加 stu 到链表中(先加入的 stu,后打印)
        list_add(&stu->list, &stu_head);
    }

    cout << "打印元素" << endl;
    
    struct list_head *pos;
    list_for_each(pos, &stu_head) {
        stu = list_entry(pos, struct student, list);
        cout << "id=" << stu->id << ", " << "score=" << stu->score << endl;
    }
    
    cout << "链表是否为空:" << list_empty(&stu_head) << endl;
    
    cout << "---------华丽的分割线---------" << endl;
    
    // 翻转链表
    list_for_each_entry_reverse(stu, &stu_head, list) {
        cout << "id=" << stu->id << ", " << "score=" << stu->score << endl;
    }

    /*
    // 通过 entry 遍历元素,不用再每次循环都执行一次 list_entry
    list_for_each_entry(stu, &stu_head, list) {
        cout << "id=" << stu->id << ", " << "score=" << stu->score << endl;
    }
    */

    /*
    // 删除元素
    struct list_head *n;
    list_for_each_safe(pos, n, &stu_head) {
    	stu = list_entry(pos, struct student, list);
    	list_del(pos);
    	free(stu);
    }
    */

    struct student *n;
    list_for_each_entry_safe(stu, n, &stu_head, list) {
        list_del(&stu->list);
        free(stu);
    }

    cout << "链表是否为空:" << list_empty(&stu_head) << endl;

    getchar();
    return 0;
}

3.3 运行一下,看看结果

控制台打印结果

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值