Skip to content

Commit f416eaa

Browse files
committed
Add 0706-design-hashmap.c
1 parent 10528de commit f416eaa

File tree

1 file changed

+117
-0
lines changed

1 file changed

+117
-0
lines changed

c/0706-design-hashmap.c

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
#define HASH_SIZE 1024
2+
3+
typedef struct HashNode {
4+
int key;
5+
int value;
6+
struct HashNode *next;
7+
} HashNode;
8+
9+
typedef struct {
10+
HashNode *hash[HASH_SIZE];
11+
} MyHashMap;
12+
13+
inline HashNode *NewHashNode(int key, int value) {
14+
HashNode *h = (HashNode*)malloc(sizeof(HashNode));
15+
h->key = key;
16+
h->value = value;
17+
h->next = NULL;
18+
return h;
19+
}
20+
21+
inline int KeyToIndex(int key) {
22+
while (key < 0) key += HASH_SIZE;
23+
return key % HASH_SIZE;
24+
}
25+
26+
MyHashMap* myHashMapCreate() {
27+
MyHashMap* h = (MyHashMap*)calloc(1, sizeof(MyHashMap));
28+
return h;
29+
}
30+
31+
void myHashMapPut(MyHashMap* obj, int key, int value) {
32+
assert(obj);
33+
HashNode **hash = &obj->hash[KeyToIndex(key)];
34+
HashNode *h = *hash;
35+
if (!*hash) {
36+
*hash = NewHashNode(key, value);
37+
} else if (h->key == key) {
38+
h->value = value;
39+
return;
40+
} else {
41+
while (h->next) {
42+
h = h->next;
43+
if (h->key == key) {
44+
h->value = value;
45+
return;
46+
}
47+
}
48+
h->next = NewHashNode(key, value);
49+
}
50+
}
51+
52+
int myHashMapGet(MyHashMap* obj, int key) {
53+
assert(obj);
54+
HashNode* hash = obj->hash[KeyToIndex(key)];
55+
while (hash) {
56+
if (hash->key == key) {
57+
return hash->value;
58+
}
59+
hash = hash->next;
60+
}
61+
return -1;
62+
}
63+
64+
void myHashMapRemove(MyHashMap* obj, int key) {
65+
assert(obj);
66+
HashNode **head = &obj->hash[KeyToIndex(key)];
67+
if (*head) {
68+
HashNode *h = *head;
69+
if (h->key == key) {
70+
HashNode *tmp = *head;
71+
*head = h->next;
72+
free(tmp);
73+
return;
74+
} else {
75+
HashNode *h_parent = h;
76+
while(h) {
77+
if (h->key == key) {
78+
h_parent->next = h->next;
79+
free(h);
80+
return;
81+
}
82+
h_parent = h;
83+
h = h->next;
84+
}
85+
}
86+
}
87+
return;
88+
}
89+
90+
void myHashMapFree(MyHashMap* obj) {
91+
if(obj) {
92+
HashNode* h;
93+
HashNode *tmp;
94+
for (int i = 0; i < HASH_SIZE; i++) {
95+
h = obj->hash[i];
96+
if(h) {
97+
while (h != NULL) {
98+
tmp = h->next;
99+
free(h);
100+
h = tmp;
101+
}
102+
}
103+
}
104+
}
105+
}
106+
107+
/**
108+
* Your MyHashMap struct will be instantiated and called as such:
109+
* MyHashMap* obj = myHashMapCreate();
110+
* myHashMapPut(obj, key, value);
111+
112+
* int param_2 = myHashMapGet(obj, key);
113+
114+
* myHashMapRemove(obj, key);
115+
116+
* myHashMapFree(obj);
117+
*/

0 commit comments

Comments
 (0)