blob: 9b6c29504f8618749d839e1729a1bc054da45f40 [file] [log] [blame]
Rob Landley7aa651a2012-11-13 17:14:08 -06001/* llist.c - Linked list functions
Rob Landley15bdc112006-11-01 22:28:46 -05002 *
3 * Linked list structures have a next pointer as their first element.
4 */
5
6#include "toys.h"
7
Rob Landley9e2b6db2012-07-15 17:22:04 -05008// Call a function (such as free()) on each element of a linked list.
9void llist_traverse(void *list, void (*using)(void *data))
Rob Landley15bdc112006-11-01 22:28:46 -050010{
Rob Landley7aa651a2012-11-13 17:14:08 -060011 while (list) {
12 void *pop = llist_pop(&list);
13 using(pop);
Rob Landleybdf037f2008-10-23 16:44:30 -050014
Rob Landley7aa651a2012-11-13 17:14:08 -060015 // End doubly linked list too.
16 if (list==pop) break;
17 }
Rob Landley15bdc112006-11-01 22:28:46 -050018}
Rob Landley0a04b3e2006-11-03 00:05:52 -050019
20// Return the first item from the list, advancing the list (which must be called
21// as &list)
22void *llist_pop(void *list)
23{
Rob Landley7aa651a2012-11-13 17:14:08 -060024 // 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;
Rob Landley0a04b3e2006-11-03 00:05:52 -050030
Rob Landley7aa651a2012-11-13 17:14:08 -060031 return (void *)next;
Rob Landley0a04b3e2006-11-03 00:05:52 -050032}
Rob Landley6ef04ef2008-01-20 17:34:53 -060033
Rob Landley2c482472012-03-12 00:25:40 -050034void dlist_add_nomalloc(struct double_list **list, struct double_list *new)
35{
Rob Landley7aa651a2012-11-13 17:14:08 -060036 if (*list) {
37 new->next = *list;
38 new->prev = (*list)->prev;
39 (*list)->prev->next = new;
40 (*list)->prev = new;
41 } else *list = new->next = new->prev = new;
Rob Landley2c482472012-03-12 00:25:40 -050042}
43
44
Rob Landley53c75042010-01-05 10:43:36 -060045// Add an entry to the end of a doubly linked list
Rob Landleybdf037f2008-10-23 16:44:30 -050046struct double_list *dlist_add(struct double_list **list, char *data)
Rob Landley6ef04ef2008-01-20 17:34:53 -060047{
Rob Landley7aa651a2012-11-13 17:14:08 -060048 struct double_list *new = xmalloc(sizeof(struct double_list));
Rob Landley6ef04ef2008-01-20 17:34:53 -060049
Rob Landley7aa651a2012-11-13 17:14:08 -060050 new->data = data;
51 dlist_add_nomalloc(list, new);
Rob Landleybdf037f2008-10-23 16:44:30 -050052
Rob Landley7aa651a2012-11-13 17:14:08 -060053 return new;
Rob Landley6ef04ef2008-01-20 17:34:53 -060054}