list_empty函数内核链表

时间:2012-10-25 17:38:50

标签: c linux-kernel linked-list kernel

list_empty()函数在./include/linux/list.h中定义,其定义为

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

list_head数据结构定义为

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

我不明白为什么内核中的此实现检查head->next == head而不是head->next == NULL&& head->prev == NULL

2 个答案:

答案 0 :(得分:7)

列表是循环的,头部本身用作虚拟节点。循环列表在插入和删除期间所需的比较数量方面略有优势。由于没有空指针,因此没有多少特殊情况需要查找。我这里没有源代码,但是如果你检查它,你会发现初始化列表是通过以下方式完成的:

head->next = head->prev = head;

插入将是:

void insert_after(struct list_head *node, struct list_head *after)
{
  node->next = after->next;
  node->prev = after;
  after->next->prev = node;
  after->next = node; 
}

看!如果声明完全没有!

答案 1 :(得分:0)

因为head->next在列表为空时不是NULL,而是指向head