Linux 核心裡到處都是鏈表,因此有必要看看它「葫蘆裡賣的是什麼藥」。先建立幾個基本認知:鏈表中元素之間是一對一關係;元素個數有限;同一個表裡各元素的型別與長度相同。
核心的 list_head 只有兩個指標 next 與 prev,本身不含任何業務資料。真正的節點結構會把 list_head 當成成員放進去,再用 list_entry 巨集從成員的位址反推回外層結構的起始位址——這正是「同一套鏈表程式碼能服務所有型別」的原因。另外,頭節點也是一個 list_head,且初始時 next 與 prev 都指向自己,於是空表與非空表的操作可以共用同一條程式路徑,不必額外判空。
#include <stdio.h>
#include <malloc.h>
// 鏈表頭結構
struct list_head
{
struct list_head *next, *prev;
};
// 鏈表頭初始化
void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
// 真正實現插入操作
void _list_add(struct list_head *nnew, struct list_head *prev, struct list_head *next)
{
next->prev = nnew;
nnew->next = next;
nnew->prev = prev;
prev->next = nnew;
}
// 向鏈表插入一個節點(預設插在頭節點之後)
void list_add(struct list_head *nnew, struct list_head *head)
{
_list_add(nnew, head, head->next);
}
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); pos = n, n = pos->next)
// 依成員在結構中的偏移量,反推節點的起始位址
#define list_entry(ptr, type, member) \
((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))
// 真正實現刪除操作
void _list_del(struct list_head *prev, struct list_head *next)
{
next->prev = prev;
prev->next = next;
}
// 刪除鏈表中的一個節點
void list_del(struct list_head *entry)
{
_list_del(entry->prev, entry->next);
entry->next = NULL;
entry->prev = NULL;
}
////////////////////////////////////////////////////
#define N 10
// 定義節點的資料結構
struct numlist
{
int num; // 資料域
struct list_head list; // 指標域
};
struct numlist numhead;
int main()
{
struct numlist *listnode;
struct list_head *pos;
struct numlist *p;
struct list_head *t;
int i;
INIT_LIST_HEAD(&numhead.list);
for (i = 0; i < N; i++)
{
listnode = (struct numlist *)malloc(sizeof(struct numlist));
listnode->num = i;
list_add(&listnode->list, &numhead.list);
printf("Node %d has been added to doublelist\n", i);
}
printf("\n\n\n\n");
// 遍歷鏈表
list_for_each(pos, &numhead.list)
{
i--;
p = list_entry(pos, struct numlist, list);
printf("Node %d's data: %d\n", i, p->num);
}
// 安全刪除:因為刪除會改動 next,先用 n 快取下一個
list_for_each_safe(pos, t, &numhead.list)
{
list_del(pos);
p = list_entry(pos, struct numlist, list);
free(p);
}
return 0;
}
兩個細節值得記住:遍歷時若要刪除節點,必須用 list_for_each_safe,因為 list_del 會把當前節點的 next 設為 NULL,一般版本會立刻失效;而 list_add 是「頭插」,所以輸出順序會與輸入相反,若需要尾部插入則要改用 list_add_tail。