2 * Copyright (c) 2011, Andy Spencer <andy753421@gmail.com>
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
22 /* Doubly linked lists */
23 list_t *list_insert(list_t *next, void *data)
25 list_t *node = new0(list_t);
28 node->prev = next ? next->prev : NULL;
29 if (node->next) node->next->prev = node;
30 if (node->prev) node->prev->next = node;
34 void list_insert_after(list_t *prev, void *data)
36 // prev must be valid,
37 // as we cannot return the original list head
38 list_t *node = new0(list_t);
41 node->next = prev->next;
43 if (node->next) node->next->prev = node;
46 list_t *list_append(list_t *head, void *data)
49 while (last && last->next)
51 list_t *node = new0(list_t);
54 if (last) last->next = node;
55 return last ? head : node;
58 list_t *list_remove(list_t *head, list_t *node, int freedata)
60 list_t *next = node->next;
61 list_t *prev = node->prev;
62 if (next) next->prev = prev;
63 if (prev) prev->next = next;
67 return head == node ? next : head;
70 int list_length(list_t *node)
73 for (; node; node = node->next)
78 list_t *list_last(list_t *list)
80 while (list && list->next)
85 list_t *list_find(list_t *list, void *data)
87 for (list_t *cur = list; cur; cur = cur->next)
88 if (cur->data == data)
94 int str2num(char *str, int def)
97 int num = strtol(str, &end, 10);
98 return end && *end == '\0' ? num : def;
101 int error(char *fmt, ...)
105 fprintf(stderr, "Error: ");
106 vfprintf(stderr, fmt, ap);
107 fprintf(stderr, "\n");