【问题标题】:list_empty function kernel linked listlist_empty 函数内核链表
【发布时间】:2013-05-07 13:14:51
【问题描述】:

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

【问题讨论】:

    标签: c linux-kernel linked-list kernel


    【解决方案1】:

    列表是循环的,头部本身充当虚拟节点。循环列表在插入和删除过程中所需的比较次数上有一点优势。由于没有空指针,所以没有那么多特殊情况需要寻找。我这里没有源代码,但是如果你检查它,你会发现初始化一个列表是通过以下方式完成的:

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

    看!根本没有 if 语句!

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-21
        • 2014-01-07
        • 1970-01-01
        相关资源
        最近更新 更多