链表 - list

链表是一种存放和操作可变数量元素(常称为节点)的数据结构。

链表与数据结构的区别:链表所包含的元素可以动态的创建并插入链表,各个元素无须占用连续内存。


1.链表分类

a. 单向链表: 这其实是一个递归。

struct list_element {

      void *data;

      struct list_element *next;

}

b. 双向链表:

struct list_element {

      void *data;

      struct list_element *next;

      struct list_element *prev;

}

c. 环形链表

单向环形链表: 单向链表的末尾元素指向头元素。

双向环形链表: 双向链表的末尾元素的 向后指针 指向头元素,头元素的 向前指针 指向末尾元素。


2. linux 内核中 链表的实现方式:

链表代码得头文件位于 include/linux/list.h 中。

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

list_head结构,经常被用来插入其他数组结构中使用,如下:

struct fox {

       unsigned long tail_length;   //狐狸尾巴长度

       unsigned long weight;     //狐狸体重

       bool          is_fantastic;  //这只狐狸优秀么?

       struct list_head list;   //所有fox结构体形成的链表

}
上面的 list.next 指向下一个元素, list.prev 指向前一个元素

3. list_entry(), 依靠这种方法,内核提供了一系列操作链表的的函数。


/**
 * 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_entry(), 其实就是container_of().

container_of() 宏定义,用来从链表指针中找到父结构中包含的任何变量。

/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:	the pointer to the member.
 * @type:	the type of the container struct this is embedded in.
 * @member:	the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({			\
	const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
	(type *)( (char *)__mptr - offsetof(type,member) );})

因为在C语言中,一个给定结构中的变量偏移 在编译时 地址就被ABI固定下来了。

所以container_of()能轻松的,可以根据一个结构体成员地址,得到该结构体的首地址,进而可以得到所有结构体成员的地址。

4. 初始化链表 --- INIT_LIST_HEAD((struct list_head *list))

static inline void INIT_LIST_HEAD(struct list_head *list)
{
	list->next = list;
	list->prev = list;
}
链表在使用之前需要初始化,常见的方式如下:

struct fox *red_fox;  //定义一个链表节点

red_fox = kmalloc(sizeof(*red_fox), GFP_KERNEL);

red_fox -> tail_length = 40;

red_fox -> weight = 6;

red_fox -> is_fantastic = false;  //节点数据初始化
 
INIT_LIST_HEAD(&red_fox -> list);  //单节点链表初始化,这个初始化后的链表只包含一个节点

如果一个结构静态创建,其中的链表需要直接引用,则可用下面的方式:

struct fox red_fox = {

    .tail_length = 40;

    .weight = 6;

    .list = LIST_HEAD_INIT(red_fox.list);

}
5. 链表头定义 --- LIST_HEAD() :
#define LIST_HEAD_INIT(name) { &(name), &(name) }

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

例:

static LIST_HEAD(fox_list);  //该函数定义并初始化了一个名为fox_list的链表

5. 链表操作: 内核提供了一组函数来操作链表。

a. list_add(struct list_head *new, struct list_head *head): 向链表中添加一个节点

/**
 * 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, struct list_head *head)
{
	__list_add(new, head, head->next);
}
/*
 * Insert a new entry between two known consecutive entries.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
#ifndef CONFIG_DEBUG_LIST
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;
}
#else
extern void __list_add(struct list_head *new,
			      struct list_head *prev,
			      struct list_head *next);
#endif
list_add_tail(struct list_head *new, struct list_head *head):项链表尾部添加一个节点。

/**
 * list_add_tail - add a new entry
 * @new: new entry to be added
 * @head: list head to add it before
 *
 * Insert a new entry before the specified head.
 * This is useful for implementing queues.
 */
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
	__list_add(new, head->prev, head);
}
b. list_del(struct list_head *entry) :从链表中删除一个节点

/**
 * list_del - deletes entry from list.
 * @entry: the element to delete from the list.
 * Note: list_empty() on entry does not return true after this, the entry is
 * in an undefined state.
 */
#ifndef CONFIG_DEBUG_LIST
static inline void list_del(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	entry->next = LIST_POISON1;
	entry->prev = LIST_POISON2;
}
#else
extern void list_del(struct list_head *entry);
#endif
/*
 * 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;
}
list_del_init(struct list_head *entry) : 从链表中删除一个节点并对其重新初始化
/**
 * list_del_init - deletes entry from list and reinitialize it.
 * @entry: the element to delete from the list.
 */
static inline void list_del_init(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	INIT_LIST_HEAD(entry);
}

c. list_move(struct list_head *list, struct list_head *head): 把节点list, 从一个链表中移除,并移到另一个链表的head节点后。

/**
 * list_move - delete from one list and add as another's head
 * @list: the entry to move
 * @head: the head that will precede our entry
 */
static inline void list_move(struct list_head *list, struct list_head *head)
{
	__list_del(list->prev, list->next);
	list_add(list, head);
}

list_move_tail(struct list_head *list, struct list_head *head) :把节点从一个链表移到另一个链表的末尾
/**
 * list_move_tail - delete from one list and add as another's tail
 * @list: the entry to move
 * @head: the head that will follow our entry
 */
static inline void list_move_tail(struct list_head *list,
				  struct list_head *head)
{
	__list_del(list->prev, list->next);
	list_add_tail(list, head);
}

d. list_empty(const struct list_head *head) : 判断链表是否为空

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

e. list_splice(const struct list_head *list, struct list_head *head):合并两个链表

/**
 * list_splice - join two lists, this is designed for stacks
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 */
static inline void list_splice(const struct list_head *list,
				struct list_head *head)
{
	if (!list_empty(list))
		__list_splice(list, head, head->next);
}
static inline void __list_splice(const struct list_head *list,
				 struct list_head *prev,
				 struct list_head *next)
{
	struct list_head *first = list->next;
	struct list_head *last = list->prev;

	first->prev = prev;
	prev->next = first;

	last->next = next;
	next->prev = last;
}
list_splice_init(struct list_head *list,  struct list_head *head) : 合并两个链表并初始化
/**
 * list_splice_init - join two lists and reinitialise the emptied list.
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 *
 * The list at @list is reinitialised
 */
static inline void list_splice_init(struct list_head *list,
				    struct list_head *head)
{
	if (!list_empty(list)) {
		__list_splice(list, head, head->next);
		INIT_LIST_HEAD(list);
	}
}

6. 遍历链表: 利用 链表 移动并访问 数据结构体。

a. 基本方法: list_for_each()宏;

/**
 * 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; prefetch(pos->next), pos != (head); \
        	pos = pos->next)
head --- 需要被遍历的 链表头节点。

每次遍历中,第一个参数不断移动指向下一个元素,知道链表中所有元素都被方位为止。

用法如下:

struct list_head *p;

list_for_each(p, list) {

     //p --- 指向链表中的元素

    //list --- 是被遍历链表的头节点
    //这其实是一个for循环
}

b. list_for_each_entry(); 遍历包含该链表的所有数据结构体

/**
 * 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.
 */
#define list_for_each_entry(pos, head, member)				\
	for (pos = list_entry((head)->next, typeof(*pos), member);	\
	     prefetch(pos->member.next), &pos->member != (head); 	\
	     pos = list_entry(pos->member.next, typeof(*pos), member))
靠list_entry()得到包含该链表的数据结构体的首地址。

使用方法:

struct fox *f;

list_for_each_entry(f, &fox_list, list) (

      //on each iteration, "f" points to the next fox structure.

)

例 inode_find_handle():

/*
 * inotify_find_handle - find the watch associated with the given inode and
 * handle
 *
 * Callers must hold inode->inotify_mutex.
 */
static struct inotify_watch *inode_find_handle(struct inode *inode,
					       struct inotify_handle *ih)
{
	struct inotify_watch *watch;  //定义变量,用来指向下一个inotify_watch数据结构

	list_for_each_entry(watch, &inode->inotify_watches, i_list) { //这其实是个for循环
		if (watch->ih == ih) //判断是不是在链表中,找到了ih数据结构,如果找到了则返回该结构
			return watch;
	}

	return NULL;
}
这里 inotify_watch 定义如下:

/*
 * struct inotify_watch - represents a watch request on a specific inode
 *
 * h_list is protected by ih->mutex of the associated inotify_handle.
 * i_list, mask are protected by inode->inotify_mutex of the associated inode.
 * ih, inode, and wd are never written to once the watch is created.
 *
 * Callers must use the established inotify interfaces to access inotify_watch
 * contents.  The content of this structure is private to the inotify
 * implementation.
 */
struct inotify_watch {
	struct list_head	h_list;	/* entry in inotify_handle's list */
	struct list_head	i_list;	/* entry in inode's list */
	atomic_t		count;	/* reference count */
	struct inotify_handle	*ih;	/* associated inotify handle */
	struct inode		*inode;	/* associated inode */
	__s32			wd;	/* watch descriptor */
	__u32			mask;	/* event mask for this watch */
};

list_for_each_entry_reverse(pos, head, 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.
 */
#define list_for_each_entry_reverse(pos, head, member)			\
	for (pos = list_entry((head)->prev, typeof(*pos), member);	\
	     prefetch(pos->member.prev), &pos->member != (head); 	\
	     pos = list_entry(pos->member.prev, typeof(*pos), member))
原理与list_for_each_entry() 一样。

c. list_for_each_entry_safe(pos, n, head, member) : 遍历的同时删除节点。

/**
 * 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, typeof(*pos), member),	\
		n = list_entry(pos->member.next, typeof(*pos), member);	\
	     &pos->member != (head); 					\
	     pos = n, n = list_entry(n->member.next, typeof(*n), member))

n --- next , 与pos类型一样,用来将下一节点存进表中,以使能安全删除当前项。

例:inotify_inode_is_dead(struct inode *inode):

/**
 * inotify_inode_is_dead - an inode has been deleted, cleanup any watches
 * @inode: inode that is about to be removed
 */
void inotify_inode_is_dead(struct inode *inode)
{
	struct inotify_watch *watch, *next; //定义2个变量,用来遍历

	mutex_lock(&inode->inotify_mutex); //上锁
	list_for_each_entry_safe(watch, next, &inode->inotify_watches, i_list) { //开始遍历
		struct inotify_handle *ih = watch->ih; //保存链表节点
		mutex_lock(&ih->mutex);
		inotify_remove_watch_locked(ih, watch); //删除 watch 节点
		mutex_unlock(&ih->mutex);
	}
	mutex_unlock(&inode->inotify_mutex);
}
EXPORT_SYMBOL_GPL(inotify_inode_is_dead);

list_for_each_entry_safe_reverse(pos, n, head, member):反向遍历删除节点用这个

/**
 * list_for_each_entry_safe_reverse - iterate backwards over list safe against removal
 * @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.
 *
 * Iterate backwards over list of given type, safe against removal
 * of list entry.
 */
#define list_for_each_entry_safe_reverse(pos, n, head, member)		\
	for (pos = list_entry((head)->prev, typeof(*pos), member),	\
		n = list_entry(pos->member.prev, typeof(*pos), member);	\
	     &pos->member != (head); 					\
	     pos = n, n = list_entry(n->member.prev, typeof(*n), member))

还有其他的链表操作函数 尽在/include/linux/list.h

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值