#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUCKET_COUNT 5
// Node for linked list in each bucket
typedef struct Node {
int key;
char value[10];
struct Node* next;
} Node;
// HashMap structure
typedef struct HashMap {
Node* buckets[BUCKET_COUNT];
} HashMap;
// Create a new node
Node* create_node(int key, const char* value) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->key = key;
strcpy(new_node->value, value);
new_node->next = NULL;
return new_node;
}
// Initialize HashMap
void init_hashmap(HashMap* map) {
for (int i = 0; i < BUCKET_COUNT; i++) {
map->buckets[i] = NULL;
}
}
// Hash function: key modulo bucket count
int hash_function(int key) {
return key % BUCKET_COUNT;
}
// Insert key-value pair into HashMap
void hashmap_insert(HashMap* map, int key, const char* value) {
int index = hash_function(key); // compute bucket index
Node* head = map->buckets[index];
// Check if key exists, update value if found
Node* curr = head;
while (curr != NULL) {
if (curr->key == key) {
strcpy(curr->value, value); // update existing value
return;
}
curr = curr->next;
}
// Insert new node at head for collision chaining
Node* new_node = create_node(key, value);
new_node->next = head;
map->buckets[index] = new_node;
}
// Print HashMap contents
void print_hashmap(HashMap* map) {
for (int i = 0; i < BUCKET_COUNT; i++) {
printf("[%d] -> ", i);
Node* curr = map->buckets[i];
while (curr != NULL) {
printf("(%d, '%s') -> ", curr->key, curr->value);
curr = curr->next;
}
printf("null\n");
}
}
int main() {
HashMap map;
init_hashmap(&map);
hashmap_insert(&map, 1, "A");
hashmap_insert(&map, 6, "B");
hashmap_insert(&map, 11, "C");
print_hashmap(&map);
return 0;
}
int index = hash_function(key); // compute bucket index
Calculate bucket index using hash function
while (curr != NULL) { if (curr->key == key) { strcpy(curr->value, value); return; } curr = curr->next; }
Check if key exists to update value instead of inserting duplicate
new_node->next = head; map->buckets[index] = new_node;
Insert new node at head of linked list to handle collisions
[0] -> null
[1] -> (11, 'C') -> (6, 'B') -> (1, 'A') -> null
[2] -> null
[3] -> null
[4] -> null