-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0706-design-hashmap.c
117 lines (104 loc) · 2.53 KB
/
0706-design-hashmap.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
115
116
117
#define HASH_SIZE 1024
typedef struct HashNode {
int key;
int value;
struct HashNode *next;
} HashNode;
typedef struct {
HashNode *hash[HASH_SIZE];
} MyHashMap;
inline HashNode *NewHashNode(int key, int value) {
HashNode *h = (HashNode*)malloc(sizeof(HashNode));
h->key = key;
h->value = value;
h->next = NULL;
return h;
}
inline int KeyToIndex(int key) {
while (key < 0) key += HASH_SIZE;
return key % HASH_SIZE;
}
MyHashMap* myHashMapCreate() {
MyHashMap* h = (MyHashMap*)calloc(1, sizeof(MyHashMap));
return h;
}
void myHashMapPut(MyHashMap* obj, int key, int value) {
assert(obj);
HashNode **hash = &obj->hash[KeyToIndex(key)];
HashNode *h = *hash;
if (!*hash) {
*hash = NewHashNode(key, value);
} else if (h->key == key) {
h->value = value;
return;
} else {
while (h->next) {
h = h->next;
if (h->key == key) {
h->value = value;
return;
}
}
h->next = NewHashNode(key, value);
}
}
int myHashMapGet(MyHashMap* obj, int key) {
assert(obj);
HashNode* hash = obj->hash[KeyToIndex(key)];
while (hash) {
if (hash->key == key) {
return hash->value;
}
hash = hash->next;
}
return -1;
}
void myHashMapRemove(MyHashMap* obj, int key) {
assert(obj);
HashNode **head = &obj->hash[KeyToIndex(key)];
if (*head) {
HashNode *h = *head;
if (h->key == key) {
HashNode *tmp = *head;
*head = h->next;
free(tmp);
return;
} else {
HashNode *h_parent = h;
while(h) {
if (h->key == key) {
h_parent->next = h->next;
free(h);
return;
}
h_parent = h;
h = h->next;
}
}
}
return;
}
void myHashMapFree(MyHashMap* obj) {
if(obj) {
HashNode* h;
HashNode *tmp;
for (int i = 0; i < HASH_SIZE; i++) {
h = obj->hash[i];
if(h) {
while (h != NULL) {
tmp = h->next;
free(h);
h = tmp;
}
}
}
}
}
/**
* Your MyHashMap struct will be instantiated and called as such:
* MyHashMap* obj = myHashMapCreate();
* myHashMapPut(obj, key, value);
* int param_2 = myHashMapGet(obj, key);
* myHashMapRemove(obj, key);
* myHashMapFree(obj);
*/