簡單搭建C工程,保證參照list.h編譯無錯即可。
在內核鏈表/include/linux/list.h中,發現原始碼提供了一個只有指針域操作的結構體型別 struct list_head。
那麼我們可以在struct list_head的基礎上設計一種帶數據域的結構。
struct list_head
{
struct list_head *next,*prev;
};
typedef struct Big_Node
{
int data;
struct list_head list;
};
內核鏈表原始碼中初始化API:
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
#define INIT_LIST_HEAD(ptr) do { \
(ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)
封裝建立頭結點介面:
P_NB Create_Node();
P_NB Create_Node()
{
P_NB node = (P_NB)malloc(sizeof(node));
if(node == NULL)
{
perror("malloc node:");
return -1;
}
INIT_LIST_HEAD(&(node->list));
return node;
}
內核鏈表原始碼中新增結點API
頭插法:
static inline void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
尾插法
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}
new :要新增的大結構體中的小結構體add_node->list
head:頭結點的小結構體
static inline void __list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
封裝頭插法尾插法:
int Head_Add_Node(P_BN head)//傳大結構體
{
if(head != NULL)
{
printf("鏈表頭爲空!\n");
return -1;
}
else
{
//建立新新增的大結構體結點
P_NB node = Create_Node();
if(node == NULL)
{
printf("新增結點失敗!\n");
return -1;
}
printf("請輸入新增的數據:");
scanf("%d",&node->data);
list_add(&(add_node->list),&(head->list));
return 0;
}
}
內核鏈表原始碼中提供遍歷:
遍歷但未獲取大結構體的地址:
從next的方向遍歷:
#define list_for_each(pos, head) \
for (pos = (head)->next, prefetch(pos->next); pos != (head); \
pos = pos->next, prefetch(pos->next))
從prev方向遍歷:
#define list_for_each_prev(pos, head) \
for (pos = (head)->prev, prefetch(pos->prev); pos != (head); \
pos = pos->prev, prefetch(pos->prev)
遍歷並且獲取大結構體的地址:
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)
#define list_for_each_entry(pos, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member), \
prefetch(pos->member.next); \
&pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member), \
prefetch(pos->member.next))
關於在遍歷大結構體中需要注意的介面:
1)通過結構體內的成員計算出結構體的地址
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
ptr: 小結構體
type:大機構的型別
member:結構體中的成員
typeof( ((type *)0)->member ):獲取小結構體的型別定義一個新的小結構體指針變數備份存放ptr
(char *)__mptr:強制裝換成字元型別指針型別
offsetof(type,member):計算member在結構體中的偏移量
(type *)(char *)__mptr - offsetof(type,member):計算出大結構體的地址,並且型別轉換爲大結構指針型別