blob: 8588721b494aada473cc83c0313046fe1464c1bf (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
/* vi: set sw=4 ts=4 :
* llist.c - Linked list functions
*
* Linked list structures have a next pointer as their first element.
*/
#include "toys.h"
// Free all the elements of a linked list
// if freeit!=NULL call freeit() on each element before freeing it.
void llist_free(void *list, void (*freeit)(void *data))
{
while (list) {
void *pop = llist_pop(&list);
if (freeit) freeit(pop);
else free(pop);
// End doubly linked list too.
if (list==pop) break;
}
}
// Return the first item from the list, advancing the list (which must be called
// as &list)
void *llist_pop(void *list)
{
// I'd use a void ** for the argument, and even accept the typecast in all
// callers as documentation you need the &, except the stupid compiler
// would then scream about type-punned pointers. Screw it.
void **llist = (void **)list;
void **next = (void **)*llist;
*llist = *next;
return (void *)next;
}
void dlist_add_nomalloc(struct double_list **list, struct double_list *new)
{
if (*list) {
new->next = *list;
new->prev = (*list)->prev;
(*list)->prev->next = new;
(*list)->prev = new;
} else *list = new->next = new->prev = new;
}
// Add an entry to the end of a doubly linked list
struct double_list *dlist_add(struct double_list **list, char *data)
{
struct double_list *new = xmalloc(sizeof(struct double_list));
new->data = data;
dlist_add_nomalloc(list, new);
return new;
}
|