#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define HASHTABLE_WIDTH 1000
#define MAX_NAME_LENGTH 128
struct node {
struct node *next;
char name[MAX_NAME_LENGTH];
int number;
};
unsigned int
hashcode(char str[MAX_NAME_LENGTH])
{
unsigned int hash = 0;
unsigned int length = strlen(str);
for (int i = 0; i < length; i++) {
hash = (hash << 2) ^ str[i];
}
return(hash);
}
void
lookup(struct node *table[HASHTABLE_WIDTH], char *key)
{
unsigned int index = hashcode(key) % HASHTABLE_WIDTH;
struct node *candidate = NULL;
if (table[index] == NULL) {
printf("Not found\n");
} else {
candidate = table[index];
while ((candidate != NULL) && strcmp(candidate->name, key)) {
candidate = candidate->next;
}
if (candidate != NULL) {
printf("%s=%d\n", candidate->name, candidate->number);
} else {
printf("Not found\n");
}
}
}
int
main()
{
int n_entries;
unsigned int index;
char temp_name[MAX_NAME_LENGTH];
struct node *new_node;
struct node *next;
struct node *table[HASHTABLE_WIDTH] = { NULL };
scanf("%d", &n_entries);
// NOTE: fill the hashtable
for (int i = 0; i < n_entries; ++i) {
new_node = calloc(1, sizeof(struct node));
scanf("%s %d", new_node->name, &new_node->number);
index = hashcode(new_node->name) % HASHTABLE_WIDTH;
if (table[index] == NULL) {
table[index] = new_node;
new_node->next = NULL;
} else {
new_node->next = table[index];
table[index] = new_node;
}
}
// NOTE: run queries
unsigned int read = 0;
do {
read = scanf("%s", temp_name);
if (read == 1) {
lookup(table, temp_name);
memset(temp_name, 0x00, MAX_NAME_LENGTH);
} else {
break;
}
} while (1);
// NOTE: cleanup
for (unsigned int i = 0; i < HASHTABLE_WIDTH; ++i) {
new_node = table[i];
while (new_node != NULL) {
next = new_node->next;
free(new_node);
new_node = next;
}
}
return(0);
}