-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashmap_C
136 lines (114 loc) · 2.45 KB
/
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 1000
struct pair
{
char *key;
int value;
struct pair *next;
};
struct hashmap
{
struct pair *table[TABLE_SIZE];
};
unsigned long hash(char *str)
{
unsigned long hash = 5381;
int c;
while ((c = *str++))
{
hash = ((hash << 5) + hash) + c;
}
return hash % TABLE_SIZE;
}
struct hashmap *create_map()
{
struct hashmap *map = malloc(sizeof(struct hashmap));
memset(map, 0, sizeof(struct hashmap));
return map;
}
void put(struct hashmap *map, char *key, int value)
{
unsigned long index = hash(key);
struct pair *pair = map->table[index];
while (pair != NULL)
{
if (strcmp(pair->key, key) == 0)
{
pair->value = value;
return;
}
pair = pair->next;
}
pair = malloc(sizeof(struct pair));
pair->key = strdup(key);
pair->value = value;
pair->next = map->table[index];
map->table[index] = pair;
}
int get(struct hashmap *map, char *key)
{
unsigned long index = hash(key);
struct pair *pair = map->table[index];
while (pair != NULL)
{
if (strcmp(pair->key, key) == 0)
{
return pair->value;
}
pair = pair->next;
}
return -1;
}
void remove_key(struct hashmap *map, char *key)
{
unsigned long index = hash(key);
struct pair *pair = map->table[index];
struct pair *prev = NULL;
while (pair != NULL)
{
if (strcmp(pair->key, key) == 0)
{
if (prev == NULL)
{
map->table[index] = pair->next;
}
else
{
prev->next = pair->next;
}
free(pair->key);
free(pair);
return;
}
prev = pair;
pair = pair->next;
}
}
void print_map(struct hashmap *map)
{
for (int i = 0; i < TABLE_SIZE; i++)
{
struct pair *pair = map->table[i];
while (pair != NULL)
{
printf("%s: %d\n", pair->key, pair->value);
pair = pair->next;
}
}
}
int main()
{
struct hashmap *map = create_map();
put(map, "one", 1);
put(map, "two", 2);
put(map, "three", 3);
put(map, "four", 4);
put(map, "five", 5);
printf("Value of key 'two': %d\n", get(map, "two"));
remove_key(map, "three");
printf("Map contents:\n");
print_map(map);
return 0;
}