#include #include #include #include /* * list macro usage examples by Peter Werner * * please see http://www.ifost.org.au/~peterw/queue.html for more info */ /* * our struct definition, with the list element to be referenced by f_link */ struct foo { int f_a; char f_b; LIST_ENTRY(foo) f_link; }; /* * the head of our list of struct foo's (see the manpage for more info) */ LIST_HEAD(listhead, foo) list; struct foo *alloc_foo(int a, char b); int main(void) { struct foo *fp, *other; struct listhead *listp; LIST_INIT(&list); listp = &list; /* * insert the elements, note the use of the f_link item */ fp = alloc_foo(1, 'a'); LIST_INSERT_HEAD(listp, fp, f_link); other = alloc_foo(2, 'b'); LIST_INSERT_AFTER(fp, other, f_link); fp = alloc_foo(3, 'c'); LIST_INSERT_BEFORE(other, fp, f_link); /* * loop through the list */ LIST_FOREACH(fp, listp, f_link) printf("%d %c\n", fp->f_a, fp->f_b); /* * free up our list */ for (fp = LIST_FIRST(listp); fp != LIST_END(listp); fp = other) { other = LIST_NEXT(fp, f_link); LIST_REMOVE(fp, f_link); free(fp); } /* * make sure */ if (LIST_EMPTY(listp)) printf("List is empty!\n"); else printf("List not empty!\n"); return(0); } struct foo * alloc_foo(int a, char b) { struct foo *tmp; tmp = (struct foo *)malloc(sizeof(struct foo)); if (tmp == NULL) err(1, "malloc"); tmp->f_a = a; tmp->f_b = b; return(tmp); }