Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf416eaa

Browse files
committed
Add 0706-design-hashmap.c
1 parent10528de commitf416eaa

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+
#defineHASH_SIZE 1024
2+
3+
typedefstructHashNode {
4+
intkey;
5+
intvalue;
6+
structHashNode*next;
7+
}HashNode;
8+
9+
typedefstruct {
10+
HashNode*hash[HASH_SIZE];
11+
}MyHashMap;
12+
13+
inlineHashNode*NewHashNode(intkey,intvalue) {
14+
HashNode*h= (HashNode*)malloc(sizeof(HashNode));
15+
h->key=key;
16+
h->value=value;
17+
h->next=NULL;
18+
returnh;
19+
}
20+
21+
inlineintKeyToIndex(intkey) {
22+
while (key<0)key+=HASH_SIZE;
23+
returnkey %HASH_SIZE;
24+
}
25+
26+
MyHashMap*myHashMapCreate() {
27+
MyHashMap*h= (MyHashMap*)calloc(1,sizeof(MyHashMap));
28+
returnh;
29+
}
30+
31+
voidmyHashMapPut(MyHashMap*obj,intkey,intvalue) {
32+
assert(obj);
33+
HashNode**hash=&obj->hash[KeyToIndex(key)];
34+
HashNode*h=*hash;
35+
if (!*hash) {
36+
*hash=NewHashNode(key,value);
37+
}elseif (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+
intmyHashMapGet(MyHashMap*obj,intkey) {
53+
assert(obj);
54+
HashNode*hash=obj->hash[KeyToIndex(key)];
55+
while (hash) {
56+
if (hash->key==key) {
57+
returnhash->value;
58+
}
59+
hash=hash->next;
60+
}
61+
return-1;
62+
}
63+
64+
voidmyHashMapRemove(MyHashMap*obj,intkey) {
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+
voidmyHashMapFree(MyHashMap*obj) {
91+
if(obj) {
92+
HashNode*h;
93+
HashNode*tmp;
94+
for (inti=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)

[8]ページ先頭

©2009-2025 Movatter.jp