-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_hashmap.c
More file actions
125 lines (102 loc) · 2.55 KB
/
string_hashmap.c
File metadata and controls
125 lines (102 loc) · 2.55 KB
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
// string key hashmap with djb2 hash func
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TABLE_SIZE 100
typedef struct HashNode{
char *key;
int value;
struct HashNode *next;
} HashNode;
typedef struct{
HashNode *buckets[TABLE_SIZE];
} HashTable;
unsigned int hash_func(const char *key){
unsigned long hash = 5381;
int c;
while ((c = *key++))
hash = ((hash << 5) + hash) + c;
return hash % TABLE_SIZE;
}
HashNode* create_node(const char *key, int value){
HashNode *new_node = (HashNode *)malloc(sizeof(HashNode));
if(!new_node){
exit(1);
}
new_node->key = strdup(key);
new_node->value = value;
new_node->next = NULL;
return new_node;
}
// Init hashtable
void init_table(HashTable *table){
for(int i = 0; i < TABLE_SIZE; i++)
table->buckets[i] = NULL;
}
void insert(HashTable *table, const char *key, int value){
unsigned int index = hash_func(key);
HashNode *new_node = create_node(key, value);
new_node->next = table->buckets[index];
table->buckets[index] = new_node;
}
int* search(HashTable *table, const char *key){
unsigned int index = hash_func(key);
HashNode *node = table->buckets[index];
while(node){
if(strcmp(node->key, key) == 0)
return &node->value;
node = node->next;
}
return NULL;
}
void delete(HashTable *table, const char *key) {
unsigned int index = hash_func(key);
HashNode *node = table->buckets[index];
HashNode *prev = NULL;
while (node) {
if (strcmp(node->key, key) == 0) {
if (prev)
prev->next = node->next;
else
table->buckets[index] = node->next;
free(node->key);
free(node);
return;
}
prev = node;
node = node->next;
}
}
// Free the entire hash table
void free_table(HashTable *table) {
for (int i = 0; i < TABLE_SIZE; i++) {
HashNode *node = table->buckets[i];
while (node) {
HashNode *temp = node;
node = node->next;
free(temp->key);
free(temp);
}
}
}
// Test the hash table
int main() {
HashTable table;
init_table(&table);
insert(&table, "Alice", 25);
insert(&table, "Bob", 30);
insert(&table, "Charlie", 22);
int *age = search(&table, "Bob");
if (age)
printf("Bob's age: %d\n", *age);
else
printf("Bob not found\n");
delete(&table, "Bob");
age = search(&table, "Bob");
if (age)
printf("Bob's age: %d\n", *age);
else
printf("Bob not found after deletion\n");
free_table(&table);
return 0;
}