struct hlist_head {
struct hlist_node *first;
};
struct hlist_node {
struct hlist_node *next;
struct hlist_node **pprev;
};
这是Linux内核代码中常用的哈希链表的结构体定义。第一个结构体存放链表头指针,first指针指向一个由hlist_node节点组成的链表,声明一个struct hlist_head数组,每个元素都指向一条链表,就形成了一个哈希表中的很多哈希桶,类似于图的邻接表。
struct hlist_node结构体中有前驱指针和后继指针,但不同于其他的数据结构,前驱指针并不是指向前一个节点,而是一个二级指针,指向前一个节点的next指针。为什么要这么设计呢,主要是为了可以统一处理节点,不必对第一个节点进行单独处理。如此一来,删除节点的函数就可以这么写:
void hlist_del(struct hlist_node *shn)
{
struct hlist_node *next = shn->next;
struct hlist_node **pprev = shn->pprev;
*pprev = next;
if (next)
{
next->pprev = pprev;
}
}
比较简洁,无须区分是否为第一个节点。