2 * Copyright (C) 2011 Andy Spencer <andy753421@gmail.com>
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 /* Doubly linked lists */
25 list_t *list_insert(list_t *next, void *data)
27 list_t *node = new0(list_t);
30 node->prev = next ? next->prev : NULL;
31 if (node->next) node->next->prev = node;
32 if (node->prev) node->prev->next = node;
36 void list_insert_after(list_t *prev, void *data)
38 // prev must be valid,
39 // as we cannot return the original list head
40 list_t *node = new0(list_t);
43 node->next = prev->next;
45 if (node->next) node->next->prev = node;
48 list_t *list_append(list_t *head, void *data)
51 while (last && last->next)
53 list_t *node = new0(list_t);
56 if (last) last->next = node;
57 return last ? head : node;
60 list_t *list_remove(list_t *head, list_t *node)
62 list_t *next = node->next;
63 list_t *prev = node->prev;
64 if (next) next->prev = prev;
65 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 error(char *fmt, ...)
98 fprintf(stderr, "Error: ");
99 vfprintf(stderr, fmt, ap);
100 fprintf(stderr, "\n");