-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.c
151 lines (119 loc) · 2.8 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
#include <stdlib.h>
#include "list.h"
#include "error.h"
static struct node *alloc_node(void *info)
{
struct node *node = calloc(1, sizeof(struct node));
if (node == NULL)
return NULL;
node->_info = info;
return node;
}
int push_back(struct node **list, void *info)
{
struct node *node = alloc_node(info);
if (node == NULL)
return -ESYSCALL;
if (*list == NULL) {
*list = node;
} else {
struct node *i = *list;
while (i->_next != NULL)
i = i->_next;
i->_next = node;
}
return 0;
}
int push_front(struct node **list, void *info)
{
struct node *node = alloc_node(info);
if (node == NULL)
return -ESYSCALL;
if (*list == NULL) {
*list = node;
} else {
node->_next = *list;
*list = node;
}
return 0;
}
void *pop_back(struct node **list)
{
if (*list == NULL)
return NULL;
if ((*list)->_next == NULL) {
void *info = (*list)->_info;
free(*list);
*list = NULL;
return info;
}
struct node *crt = *list;
struct node *prev = NULL;
while (crt->_next != NULL) {
prev = crt;
crt = crt->_next;
}
prev->_next = NULL;
void *info = crt->_info;
free(crt);
return info;
}
void *pop_front(struct node **list)
{
if (*list == NULL)
return NULL;
struct node *tmp = *list;
(*list) = (*list)->_next;
void *info = tmp->_info;
free(tmp);
return info;
}
void free_list(struct node **list, void (*delete_handle)(void*))
{
if (delete_handle == NULL) {
// no delete handle provided, don't delete info
struct node *i = *list;
while (i != NULL) {
struct node *tmp = i;
i = i->_next;
free(tmp);
}
*list = NULL;
} else {
struct node *i = *list;
while (i != NULL) {
struct node *tmp = i;
i = i->_next;
(*delete_handle)(tmp->_info);
free(tmp);
}
*list = NULL;
}
}
void *pop_element(struct node **list, void *ref,
int (*cmp_handle)(void*, void*))
{
if (*list == NULL)
return NULL;
if (cmp_handle(ref, (*list)->_info)) {
// first element, just pop front
return pop_front(list);
}
struct node *crt = *list;
struct node *prev = NULL;
while (crt != NULL) {
if (cmp_handle(crt->_info, ref)) {
if (crt->_next == NULL)
return pop_back(list);
struct node *tmp = crt;
prev->_next = crt->_next;
void *info = tmp->_info;
free(tmp);
return info;
}
prev = crt;
crt = crt->_next;
}
// if function reaches this point => no match
return NULL;
}