双向链表节点数据结构:
1 struct list_head { 2 struct list_head *next, *prev; 3 };
链表的初始化:
1 static inline void INIT_LIST_HEAD(struct list_head *list) 2 { 3 list->next = list; 4 list->prev = list; 5 }
添加一个节点:
1 static inline void list_add(struct list_head *new, struct list_head *head) 2 { 3 __list_add(new, head, head->next); // new插入到head的后面,head->next的前面 4 } 5 6 static inline void __list_add(struct list_head *new, 7 struct list_head *prev, 8 struct list_head *next) 9 { 10 next->prev = new; 11 new->next = next; 12 new->prev = prev; 13 prev->next = new; 14 }
检查链表是否为空,返回1表示空:
1 /** 2 * list_empty - tests whether a list is empty 3 * @head: the list to test. 4 */ 5 static inline int list_empty(const struct list_head *head) 6 { 7 return head->next == head; 8 }
宏 list_for_each
功能:遍历循环双向链表。
参数head:从head节点处开始遍历循环双向链表;
参数pos: 循环变量,类似for循环的i;
1 #define list_for_each(pos, head) \ 2 for (pos = (head)->next; pos != (head); \ 3 pos = pos->next)