blob: 8588721b494aada473cc83c0313046fe1464c1bf [file] [log] [blame]
Rob Landley15bdc112006-11-01 22:28:46 -05001/* 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
12void llist_free(void *list, void (*freeit)(void *data))
13{
14 while (list) {
Rob Landley0a04b3e2006-11-03 00:05:52 -050015 void *pop = llist_pop(&list);
16 if (freeit) freeit(pop);
Rob Landleybdf037f2008-10-23 16:44:30 -050017 else free(pop);
18
19 // End doubly linked list too.
20 if (list==pop) break;
Rob Landley15bdc112006-11-01 22:28:46 -050021 }
22}
Rob Landley0a04b3e2006-11-03 00:05:52 -050023
24// Return the first item from the list, advancing the list (which must be called
25// as &list)
26void *llist_pop(void *list)
27{
28 // I'd use a void ** for the argument, and even accept the typecast in all
29 // callers as documentation you need the &, except the stupid compiler
30 // would then scream about type-punned pointers. Screw it.
31 void **llist = (void **)list;
32 void **next = (void **)*llist;
33 *llist = *next;
34
35 return (void *)next;
36}
Rob Landley6ef04ef2008-01-20 17:34:53 -060037
Rob Landley2c482472012-03-12 00:25:40 -050038void dlist_add_nomalloc(struct double_list **list, struct double_list *new)
39{
40 if (*list) {
41 new->next = *list;
42 new->prev = (*list)->prev;
43 (*list)->prev->next = new;
44 (*list)->prev = new;
45 } else *list = new->next = new->prev = new;
46}
47
48
Rob Landley53c75042010-01-05 10:43:36 -060049// Add an entry to the end of a doubly linked list
Rob Landleybdf037f2008-10-23 16:44:30 -050050struct double_list *dlist_add(struct double_list **list, char *data)
Rob Landley6ef04ef2008-01-20 17:34:53 -060051{
Rob Landley2c482472012-03-12 00:25:40 -050052 struct double_list *new = xmalloc(sizeof(struct double_list));
Rob Landley6ef04ef2008-01-20 17:34:53 -060053
Rob Landley2c482472012-03-12 00:25:40 -050054 new->data = data;
55 dlist_add_nomalloc(list, new);
Rob Landleybdf037f2008-10-23 16:44:30 -050056
Rob Landley2c482472012-03-12 00:25:40 -050057 return new;
Rob Landley6ef04ef2008-01-20 17:34:53 -060058}