-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.c
86 lines (71 loc) · 1.45 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
/* Copyright 2023 Sima Alexandru (312CA) */
#include "list.h"
#include "utils.h"
list *list_create_node(void *key, void *value)
{
list *node = malloc(sizeof(list));
DIE(!node, "failed malloc() of list");
node->info.key = key;
node->info.data = value;
node->next = NULL;
return node;
}
void list_push(list **l, list *node)
{
if (!*l) {
node->next = NULL;
*l = node;
return;
}
node->next = *l;
*l = node;
}
void *list_get_item(list *l, void *key, int (*compare_func)(void *, void *))
{
while (l) {
if (compare_func(l->info.key, key) == 0)
return l->info.data;
l = l->next;
}
return NULL;
}
list *list_extract_item(list **l, void *key,
int (*compare_func)(void *, void *))
{
list *prev = NULL;
list *curr = *l;
while (curr) {
if (compare_func(curr->info.key, key) == 0) {
if (prev)
prev->next = curr->next;
else
*l = curr->next;
return curr;
}
prev = curr;
curr = curr->next;
}
return NULL;
}
void list_split(list *src, list **accepted, list **rejected,
unsigned int min_hash, unsigned int max_hash)
{
while (src) {
list *curr = src;
src = src->next;
unsigned int hash = hash_function_key(curr->info.key);
if (min_hash <= hash && hash < max_hash)
list_push(accepted, curr);
else
list_push(rejected, curr);
}
}
void list_destroy(list *l, void (*destructor_func)(void *, void *))
{
while (l) {
list *next = l->next;
destructor_func(l->info.key, l->info.data);
free(l);
l = next;
}
}