2 list.c -- functions to deal with double linked lists
3 Copyright (C) 2000-2005 Ivo Timmermans
4 2000-2006 Guus Sliepen <guus@tinc-vpn.org>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 /* (De)constructors */
28 list_t *list_alloc(list_action_t delete)
32 list = xmalloc_and_zero(sizeof(list_t));
33 list->delete = delete;
38 void list_free(list_t *list)
43 list_node_t *list_alloc_node(void)
45 return xmalloc_and_zero(sizeof(list_node_t));
48 void list_free_node(list_t *list, list_node_t *node)
50 if(node->data && list->delete)
51 list->delete(node->data);
56 /* Insertion and deletion */
58 list_node_t *list_insert_head(list_t *list, void *data)
62 node = list_alloc_node();
66 node->next = list->head;
70 node->next->prev = node;
79 list_node_t *list_insert_tail(list_t *list, void *data)
83 node = list_alloc_node();
87 node->prev = list->tail;
91 node->prev->next = node;
100 void list_unlink_node(list_t *list, list_node_t *node)
103 node->prev->next = node->next;
105 list->head = node->next;
108 node->next->prev = node->prev;
110 list->tail = node->prev;
115 void list_delete_node(list_t *list, list_node_t *node)
117 list_unlink_node(list, node);
118 list_free_node(list, node);
121 void list_delete_head(list_t *list)
123 list_delete_node(list, list->head);
126 void list_delete_tail(list_t *list)
128 list_delete_node(list, list->tail);
131 /* Head/tail lookup */
133 void *list_get_head(list_t *list)
136 return list->head->data;
141 void *list_get_tail(list_t *list)
144 return list->tail->data;
149 /* Fast list deletion */
151 void list_delete_list(list_t *list)
153 list_node_t *node, *next;
155 for(node = list->head; node; node = next) {
157 list_free_node(list, node);
165 void list_foreach_node(list_t *list, list_action_node_t action)
167 list_node_t *node, *next;
169 for(node = list->head; node; node = next) {
175 void list_foreach(list_t *list, list_action_t action)
177 list_node_t *node, *next;
179 for(node = list->head; node; node = next) {