第一 聲明和初始化,我在這裡不詳細說明了,請看我上一篇博文,在這裡貼出相應的代碼:
#ifndef _LINUX_LIST_H#define _LINUX_LIST_H#define offsetof1(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)#define container_of(ptr, type, member) ( { \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof1(type,member) ); } )static inline void prefetch(const void *x) {;}static inline void prefetchw(const void *x) {;}//#define LIST_POISON1 ((void *) 0x00100100)//#define LIST_POISON2 ((void *) 0x00200200)#define LIST_POISON1 0#define LIST_POISON2 0struct list_head { struct list_head *next, *prev; //雙向鏈表};#define LIST_HEAD_INIT(name) { &(name), &(name) } //用同一對象初始化next 和prev.#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)
下面就是插入函數的具體分析,其實插入函數很簡單,只要學過C語言的都能懂,我在這裡只是簡單解釋下:
/** Insert a new entry between two known consecutive entries.** This is only for internal list manipulation where we know* the prev/next entries already!*/static inline void __list_add(struct list_head *new1, //插入新條目,插在prev與next中間 struct list_head *prev, // struct list_head *next){ next->prev = new1; new1->next = next; new1->prev = prev; prev->next = new1;}/*** list_add - add a new entry* @new: new entry to be added* @head: list head to add it after** Insert a new entry after the specified head.* This is good for implementing stacks.*/static inline void list_add(struct list_head *new1, struct list_head *head) //頭插法,調用_list_add()實現{ __list_add(new1, head, head->next);}/*** list_add_tail - add a new entry* @new: new entry to be added* @head: list head to add it before** Insert a new entry before the specified head.* This is useful for implementing queues.*/static inline void list_add_tail(struct list_head *new1, struct list_head *head) //尾部插法{ __list_add(new1, head->prev, head);}