-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex07_part2.c
More file actions
76 lines (67 loc) · 1.58 KB
/
Copy pathex07_part2.c
File metadata and controls
76 lines (67 loc) · 1.58 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
/*
** EPITECH PROJECT, 2024
** ppool04pm
** File description:
** ex07_part2
*/
#include <stdbool.h>
#include <stdlib.h>
#include "map.h"
bool map_add_elem(
map_t **map_ptr,
void *key,
void *value,
key_comparator_t key_cmp)
{
map_t **ptr = map_ptr;
pair_t *pair;
int cmp = 0;
if (map_ptr == NULL || key == NULL || key_cmp == NULL)
return false;
for (; *ptr != NULL && cmp <= 0; ptr = &(*ptr)->next) {
pair = (*ptr)->value;
if (pair == NULL)
return false;
cmp = key_cmp(pair->key, key);
if (cmp == 0) {
pair->value = value;
return true;
}
}
pair = malloc(sizeof(pair_t));
*pair = (pair_t){key, value};
list_add_elem_at_front(ptr, pair);
return true;
}
void *map_get_elem(map_t *map, void *key, key_comparator_t key_cmp)
{
pair_t *pair;
while (map != NULL) {
pair = map->value;
if (key_cmp(pair->key, key) == 0)
return pair->value;
map = map->next;
}
return NULL;
}
bool map_del_elem(map_t **map_ptr, void *key, key_comparator_t key_cmp)
{
pair_t *pair;
while (*map_ptr != NULL) {
pair = (*map_ptr)->value;
if (pair != NULL && key_cmp(pair->key, key) == 0) {
free(pair);
return list_del_elem_at_front(map_ptr);
}
map_ptr = &(*map_ptr)->next;
}
return false;
}
void map_clear(map_t **map_ptr)
{
while (*map_ptr != NULL) {
if ((*map_ptr)->value != NULL)
free((*map_ptr)->value);
list_del_elem_at_front(map_ptr);
}
}