Linux双向链表(二)——逻辑判断

本文详细介绍了Linux双链表的逻辑判断方法,包括如何判断结点是否为链表末尾、链表是否为空、不安全的空链表判断方式以及如何确定链表仅包含一个结点。这些判断在链表操作中起到关键作用,防止潜在的运行错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

双链表判断函数

1、判断结点是不是链表head的最后一个结点

/**
 * list_is_last - tests whether @list is the last entry in list @head
 * @list: the entry to test
 * @head: the head of the list
 */
static inline int list_is_last(const struct list_head *list,
				const struct list_head *head)
{
	return list->next == head;
}


方法很简单:检测 list指向的entry的next结点是否是head,如果是,则返回true,否则,返回false!

用途:对于有序链表,从头遍历链表,需要这样做遍历结束条件

2、判断链表是否为空

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

上篇博文可知在链表初始化时,宏定义

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

把name的next和prev初始化为指向自身,以表示链表为空。由此,返回head->next == head的逻辑值即可。

返回值:如果链表为空,返回true,否则返回false

用途:操纵一个链表时,首先要保证链表非空,否则,可能导致潜在运行bug

3、不安全方式(并行时)判断链表是否为空

/**
 * list_empty_careful - tests whether a list is empty and not being modified
 * @head: the list to test
 *
 * Description:
 * tests whether a list is empty _and_ checks that no other CPU might be
 * in the process of modifying either member (next or prev)
 *
 * NOTE: using list_empty_careful() without synchronization
 * can only be safe if the only activity that can happen
 * to the list entry is list_del_init(). Eg. it cannot be used
 * if another CPU could re-list_add() it.
 */
static inline int list_empty_careful(const struct list_head *head)
{
	struct list_head *next = head->next;//局部变量保存,如果未执行return之前,另CPU操作了链表,结果是不正确的,因此在并行架构上要“careful”——小心使用,具体细节看上面代码作者的注释	return (next == head) && (next == head->prev);
}

4、判断链表是否只有一个结点

/**
 * list_is_singular - tests whether a list has just one entry.
 * @head: the list to test.
 */
static inline int list_is_singular(const struct list_head *head) 
{
	return !list_empty(head) && (head->next == head->prev);//非空且只有一个,使用图中①②
}


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>声明<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>     知识要传播,劳动要尊重! 受益于开源,回馈于社会! 大家共参与,服务全人类!     

>>     本博文由my_live_123原创(http://blog.youkuaiyun.com/cwcmcw),转载请注明出处!   

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>^_^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值