-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommon_list.c
More file actions
78 lines (73 loc) · 1.52 KB
/
common_list.c
File metadata and controls
78 lines (73 loc) · 1.52 KB
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
#include "common_list.h"
int init_list(struct common_list **l)
{
(*l) = (struct common_list *) malloc(sizeof(struct common_list));
if(*l == NULL) {
perror("malloc: ");
return -1;
}
(*l)->data = NULL;
(*l)->next = NULL;
return 0;
}
int insert_node(struct common_list *l, void *d, void *(*func)(void *))
{
struct common_list *node = (struct common_list *) malloc(sizeof(struct common_list));
if(node == NULL) {
perror("malloc: ");
return -1;
}
/*void *ptr = malloc(size);
if(ptr == NULL) {
perror("malloc: ");
return -1;
}
memcpy(ptr, d, size);*/
node->data = func(d);
node->next = l->next;
l->next = node;
return 0;
}
int remove_node(struct common_list *l, void *d, int (*func)(void *, void *))
{
struct common_list *p = l->next;
struct common_list *prev = l;
while(p) {
if(func(p->data, d) != 0) {
prev = p;
p = p->next;
} else {
prev->next = p->next;
free(p);
return 0;
}
}
return 1;
}
struct common_list *find_node(struct common_list *l, void *d, int (*func)(void *, void *))
{
struct common_list *p = l->next;
while(p) {
if(func(p->data, d) != 0) {
p = p->next;
} else {
return p;
}
}
return NULL; /* not found */
}
int clear_list(struct common_list *l, int (*func)(void *))
{
struct common_list *p = l->next;
struct common_list *tmp = p;
while(tmp) {
tmp = p->next;
//free(p->data);
//free(p);
func(p->data);
free(p);
p = tmp;
}
free(l);
return 0;
}