#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
目的:
它实际上是一个for循环,从第一个节点开始(链表头不算做节点),pos = 第1个节点指针; 然后又向后移动一个节点,
pos = 第2个节点指针...;直到到达最后一个节点为止
其他:
list_for_each_prev // 由后向前遍历
list_for_each_prev_safe // 安全的遍历(遍历过程中要删除节点是使用)
其机制是我们多传入一个struct list_t的指针n,用于指向pos的下一个节点,
以保证我们在删除pos指向的节点时,仍能继续遍历链表的剩余节点。
试想一下: 如果使用#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
来遍历链表, 每遍历一次就删除当前节点, 那么pos = pos->next就会出错
举例:
#include "list.h"
#include <stdio.h>
static LIST_HEAD (head);
typedef struct T
{ char *name;
list_t member; // pre, next
}type;
int main(int argc, char **argv)
{
type a,b,c,d;
list_t *ptr; // 节点指针
type *t;
a.name = "a";
b.name = "b";
c.name = "c";
d.name = "d";
list_add(&a.member, &head); // 紧挨着链表头插入新节点
list_add(&b.member, &head); // 紧挨着链表头插入新节点
list_add(&c.member, &head); // 紧挨着链表头插入新节点
list_add(&d.member, &head); // 紧挨着链表头插入新节点
list_for_each(ptr, &head)
{ t = list_entry(ptr, type, member);
printf("%s\n", t->name);
}
return 0;
}
结果:
/*
book@gui_hua_shu:~/test$ ./a.out
d
c
b
a
*/