在C 语言中双链表的实现,已经有很多经典的实现,下面的代码,从 android 中摘取,事实上这段代码可能 google 的人最初从linux 的代码中学得,其实设置到了极限,都达到了设计的完美,那么大家几乎说就是一样了,因我完美是唯一的,对于同一个事物的抽线,最完美的表达是唯一的。
struct listnode
{
struct listnode *next;
struct listnode *prev;
};
#define node_to_item(node, container, member) \
(container *) (((char*) (node)) - offsetof(container, member))
#define list_declare(name) \
struct listnode name = { \
.next = &name, \
.prev = &name, \
}
#define list_for_each(node, list) \
for (node = (list)->next; node != (list); node = node->next)
#define list_for_each_reverse(node, list) \
for (node = (list)->prev; node != (list); node = node->prev)
void list_init(struct listnode *list);
void list_add_tail(struct listnode *list, struct listnode *item);
void list_remove(struct listnode *item);
#define list_empty(list) ((list) == (list)->next)
#define list_head(list) ((list)->next)
#define list_tail(list) ((list)->prev)
摘录一段参考代码:
void service_for_each(void (*func)(struct service *svc))
{
struct listnode *node;
struct service *svc;
list_for_each(node, &service_list) {
svc = node_to_item(node, struct service, slist);
func(svc);
}
}
struct service *service_find_by_name(const char *name)
{
struct listnode *node;
struct service *svc;
list_for_each(node, &service_list) {
svc = node_to_item(node, struct service, slist);
if (!strcmp(svc->name, name)) {
return svc;
}
}
return 0;
}