-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.c
114 lines (84 loc) · 1.59 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
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "list.h"
#if 0
static void
dump_list(const struct list *l)
{
struct node *n = l->first;
while (n) {
printf("n == %p\n", n);
printf("n->data == %p\n", n->data);
printf("n->prev == %p\n", n->prev);
printf("n->next == %p\n", n->next);
printf("-----\n");
n = n->next;
}
putchar('\n');
}
#endif
struct list *
list_new(void)
{
struct list *l;
l = malloc(sizeof *l);
l->size = 0;
l->first = NULL;
return l;
}
void
list_add(struct list *l, void *data)
{
struct node *n;
n = malloc(sizeof *n);
n->data = data;
n->next = l->first;
n->prev = NULL;
if (l->first)
l->first->prev = n;
l->first = n;
l->size++;
}
void *
list_remove(struct list *l, struct node *n)
{
void *data = n->data;
if (n->prev) {
n->prev->next = n->next;
} else {
l->first = n->next;
}
if (n->next) {
n->next->prev = n->prev;
}
free(n);
l->size--;
assert(l->size >= 0);
return data;
}
void
list_free(struct list *l, list_free_func free_func)
{
struct node *current;
struct node *next;
void *data;
if (free_func == NULL)
free_func = free;
current = l->first;
while (current) {
next = current->next;
data = list_remove(l, current);
free_func(data);
current = next;
}
free(l);
}
int list_empty(const struct list *l)
{
return (l->first == NULL) ? 1 : 0;
}
int list_size(const struct list *l)
{
return l->size;
}