-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.c
More file actions
134 lines (101 loc) · 2.22 KB
/
map.c
File metadata and controls
134 lines (101 loc) · 2.22 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
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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "map.h"
#include "debug.h"
Map* Map_create() {
Map *map = malloc(sizeof(Map));
assert(map != NULL);
map->first = NULL;
map->last = NULL;
map->length = 0;
map->not_found_val = NULL;
return map;
}
void Map_clear(Map* map) {
if (map->length > 0) {
struct MapNode *node = map->first;
for (int i = 0; i < map->length; i++) {
struct MapNode *next = node->next;
free(node);
node = next;
}
}
map->first = NULL;
map->last = NULL;
map->length = 0;
}
void Map_destroy(Map *map) {
assert(map != NULL);
Map_clear(map);
free(map);
}
void* _Map_get_node(Map* map, char* key) {
for (struct MapNode* node = map->first; node != NULL; node = node->next) {
if (strcmp(node->key, key) == 0) {
return node;
}
}
return NULL;
}
void Map_set(Map *map, char* key, void *data) {
struct MapNode* node = _Map_get_node(map, key);
if (node != NULL) {
node->data = data;
return;
}
node = malloc(sizeof(struct MapNode));
assert(node != NULL);
node->data = data;
node->key = key;
node->next = NULL;
node->prev = NULL;
// map is empty
if (map->length == 0) {
map->first = node;
map->last = node;
} else { // map is not empty
// link nodes together
map->last->next = node;
node->prev = map->last;
map->last = node;
}
map->length++;
}
void* Map_get(Map* map, char* key) {
struct MapNode* node = _Map_get_node(map, key);
if (node == NULL) return map->not_found_val;
return node->data;
}
void* Map_del(Map *map, char* key) {
sentinel("not yet implemented");
// if (map->length == 0) {
// return NULL;
// }
void *data = map->last->data;
// if (map->length == 1) {
// free(map->last);
// map->last = NULL;
// map->first = NULL;
// }
// if (map->length > 1) {
// struct MapNode *removee = map->last;
// map->last = removee->prev;
// free(removee);
// map->last->next = NULL;
// }
// map->length--;
return data;
error:
return NULL;
}
void Map_print(Map *map) {
printf("Map is at memory location: %p\n", map);
printf("Length: %d\n", map->length);
struct MapNode *node = map->first;
for (int i = 0; i < map->length; i++) {
// printf("\t%d\n", node->data);
node = node->next;
}
}