双链表判断函数
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),转载请注明出处!
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>^_^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<