list.h
#ifndef IF_LIST #define IF_LIST #define LIST_HEAD_INIT(x) list_head x={&x, &x} #define LIST_HEAD_INIT_STATIC(x) static LIST_HEAD_INIT(x) struct __list_head { struct __list_head* prev; struct __list_head* next; }; typedef struct __list_head list_head; inline int list_empty(list_head* head); inline void list_add(list_head* head, list_head* t); inline void list_add_tail(list_head* head, list_head* t); inline void list_del(list_head* t); inline list_head* list_first(list_head* t); inline list_head* list_takefirst(list_head* head); inline int list_count(list_head* t); inline void list_init(list_head* head); #define list_entry(p, t, list) / (t*)((char*)p - (char*)(&(((t*)0)->list))) #define list_for_each(p, x) / for(p=(x)->next;p!=(x);p=p->next) #endif
list.c
#include "list.h" inline int list_empty(list_head* head) { return head->next == head; } inline void list_add(list_head* head, list_head* t) { list_head* tmp = head->next; t->prev = head; t->next = tmp; tmp->prev = t; head->next = t; } inline void list_add_tail(list_head* head, list_head* t) { t->prev = head->prev; t->next = head; t->prev->next = t; head->prev = t; } inline void list_del(list_head* t) { t->prev->next = t->next; t->next->prev = t->prev; } inline list_head* list_first(list_head* t) { return list_empty(t)?0:t->next; } inline list_head* list_takefirst(list_head* head) { list_head* ret = head->next; list_del(ret); return ret; } inline int list_count(list_head* t) { int ret = 0; list_head* head = t; while(t->next != head) { t=t->next; ++ret; } return ret; } inline void list_init(list_head* head) { head->next = head->prev = head; }
测试代码
main.c
main.c