-
Notifications
You must be signed in to change notification settings - Fork 5
/
dict.c
114 lines (96 loc) · 2.6 KB
/
dict.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
#include "dict.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct dict *dict_create() {
struct dict *d = (struct dict*)malloc(sizeof(struct dict));
d->head = NULL;
return d;
}
void dict_free(struct dict *d) {
if (d == NULL)
return;
struct dict_item *head = d->head;
struct dict_item *tmp;
while (head != NULL) {
tmp = head;
head = head->next;
free(tmp->key);
free(tmp->value);
free(tmp);
}
free(d);
}
int dict_has(const struct dict *d, const char *key) {
if (d == NULL)
return 0;
struct dict_item *current_item = d->head;
while (current_item != NULL) {
if (!strcmp(current_item->key, key))
return 1; // found
current_item = current_item->next;
}
return 0;
}
char *dict_get(const struct dict *d, const char *key) {
if (d == NULL)
return NULL;
struct dict_item *current_item = d->head;
while (current_item != NULL) {
if (!strcmp(current_item->key, key))
return current_item->value; // found -> return
current_item = current_item->next;
}
return NULL;
}
int dict_del(struct dict *d, const char * key) {
//TODO free string
if (d == NULL)
return -1;
struct dict_item *current_item = d->head;
struct dict_item *prev = NULL;
while (current_item != NULL) {
if (!strcmp(current_item->key, key)) {
// found -> delete
if (prev)
prev->next = current_item->next;
else
d->head = current_item->next;
free(current_item);
return 0;
}
prev = current_item;
current_item = current_item->next;
}
return -1;
}
int dict_set(struct dict *d, char *key, char *val) {
if (d == NULL)
return -1;
if (d->head == NULL) {
//empty dict
struct dict_item *new = (struct dict_item *)malloc(sizeof(struct dict_item));
new->key = key;
new->value = val;
new->next = NULL;
d->head = new;
return 0;
}
struct dict_item *current_item = d->head;
struct dict_item *prev = NULL;
while (current_item != NULL) {
if (!strcmp(current_item->key, key)) {
// found -> replace
current_item->value = val;
return 0;
}
prev = current_item;
current_item = current_item->next;
}
struct dict_item *new = (struct dict_item *)malloc(sizeof(struct dict_item));
new->key = key;
new->value = val;
new->next = NULL;
prev->next = new;
return 0;
}