Rob Landley | 15bdc11 | 2006-11-01 22:28:46 -0500 | [diff] [blame] | 1 | /* vi: set sw=4 ts=4 : |
| 2 | * llist.c - Linked list functions |
| 3 | * |
| 4 | * Linked list structures have a next pointer as their first element. |
| 5 | */ |
| 6 | |
| 7 | #include "toys.h" |
| 8 | |
| 9 | // Free all the elements of a linked list |
| 10 | // if freeit!=NULL call freeit() on each element before freeing it. |
| 11 | |
| 12 | void llist_free(void *list, void (*freeit)(void *data)) |
| 13 | { |
| 14 | while (list) { |
Rob Landley | 0a04b3e | 2006-11-03 00:05:52 -0500 | [diff] [blame] | 15 | void *pop = llist_pop(&list); |
| 16 | if (freeit) freeit(pop); |
Rob Landley | 15bdc11 | 2006-11-01 22:28:46 -0500 | [diff] [blame] | 17 | } |
| 18 | } |
Rob Landley | 0a04b3e | 2006-11-03 00:05:52 -0500 | [diff] [blame] | 19 | |
| 20 | // Return the first item from the list, advancing the list (which must be called |
| 21 | // as &list) |
| 22 | void *llist_pop(void *list) |
| 23 | { |
| 24 | // I'd use a void ** for the argument, and even accept the typecast in all |
| 25 | // callers as documentation you need the &, except the stupid compiler |
| 26 | // would then scream about type-punned pointers. Screw it. |
| 27 | void **llist = (void **)list; |
| 28 | void **next = (void **)*llist; |
| 29 | *llist = *next; |
| 30 | |
| 31 | return (void *)next; |
| 32 | } |
Rob Landley | 6ef04ef | 2008-01-20 17:34:53 -0600 | [diff] [blame^] | 33 | |
| 34 | // Add an entry to the end off a doubly linked list |
| 35 | void dlist_add(struct double_list **list, char *data) |
| 36 | { |
| 37 | struct double_list *line = xmalloc(sizeof(struct double_list)); |
| 38 | |
| 39 | line->data = data; |
| 40 | if (*list) { |
| 41 | line->next = *list; |
| 42 | line->prev = (*list)->prev; |
| 43 | (*list)->prev->next = line; |
| 44 | (*list)->prev = line; |
| 45 | } else *list = line->next = line->prev = line; |
| 46 | } |