-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdict.c
95 lines (76 loc) · 1.67 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
#include "dict.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct Node_t{
char *key;
unsigned int value;
struct Node_t *next;
} Node;
struct Dict_t {
Node *first;
unsigned int nkeys;
};
Dict *dictCreate(void){
Dict *d = malloc(sizeof(Dict));
d -> first = NULL;
d -> nkeys = 0;
return d;
}
void dictFree(Dict *d){
Node *p = d -> first;
while(p != NULL){
d -> first = p;
p = p -> next;
free(d -> first);
}
free(d);
return;
}
void dictInsert(Dict *d, char *key, int value){
Node *p = d -> first;
if(p == NULL){
d -> first = malloc(sizeof(Node));
p = d -> first;
p -> value = value;
p -> key = strdup(key);
p -> next = NULL;
return;
}
while(1){
if(strcmp(p -> key, key) == 0){
p -> value = value;
return;
}
if(p -> next == NULL) break;
p = p -> next;
}
p -> next = malloc(sizeof(Node));
p = p -> next;
p -> value = value;
p -> key = strdup(key);
p -> next = NULL;
return;
}
void dictAdd(Dict *d, char *key, int inc){
int val = dictSearch(d, key);
if(val == -1) dictInsert(d, key, inc);
else dictInsert(d, key, inc+val);
return;
}
int dictSearch(Dict *d, char *key){
if(d -> first == NULL) return -1;
Node *p = d -> first;
while(p != NULL){
if(strcmp(p -> key, key) == 0){
return p -> value;
}
p = p -> next;
}
return -1;
}
void dictPrint(Dict *d){
for(Node *p = d -> first; p != NULL; p = p -> next)
printf("%s\t%d\n", p -> key, p -> value);
return;
}