/
list.c
152 lines (126 loc) · 2.52 KB
/
list.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/* @(#)list.c
*
* Copyright 2005 Liam Stewart
*
* This file is part of the MATLAB LBFGS wrapper.
*
* The MATLAB LBFGS wrapper is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The MATLAB LBFGS wrapper is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "list.h"
#include "utils.h"
#include <assert.h>
list_t *
list_init()
{
list_t *l = XMALLOC_P(list_t, 1);
l->next_id = 0;
l->head = NULL;
return l;
}
lid_t
list_add(list_t *l, void *data)
{
list_item_t *li;
assert(l != NULL);
assert(data != NULL);
li = XMALLOC_P(list_item_t, 1);
li->data = data;
li->next = NULL;
li->id = l->next_id++;
if (l->head == NULL)
{
l->head = li;
}
else
{
li->next = l->head;
l->head = li;
}
return li->id;
}
void *
list_find(list_t *l, lid_t id)
{
list_item_t *p;
assert(l != NULL);
p = l->head;
while (p != NULL)
{
if (p->id == id)
return p->data;
p = p->next;
}
return NULL;
}
void *
list_remove(list_t *l, lid_t id)
{
void *data;
list_item_t *p, *q;
assert(l != NULL);
data = NULL;
p = l->head, q = NULL;
while (p != NULL)
{
if (p->id == id)
{
if (q != NULL)
q->next = p->next;
else /* p is head */
l->head = p->next;
p->next = NULL;
data = p->data;
XFREE(p);
break;
}
else
{
q = p;
p = p->next;
}
}
return data;
}
void
list_delete(list_t *l, lid_t id, void(*dtor)(void *))
{
void *data;
assert(l != NULL);
data = list_remove(l, id);
if (data != NULL && dtor != NULL)
dtor(data);
}
void
list_clean(list_t *l, void(*dtor)(void *))
{
list_item_t *p;
assert(l != NULL);
while (l->head != NULL)
{
p = l->head;
l->head = p->next;
assert(p->data != NULL);
if (dtor != NULL)
dtor(p->data);
XFREE(p);
}
l->next_id = 0;
}
void
list_destroy(list_t *l, void(*dtor)(void *))
{
list_clean(l, dtor);
XFREE(l);
}