You are on page 1of 2

#include <stdio.

h>
#include <stdlib.h>
#include <string.h>

#define TABLE_SIZE 10

struct Node {
char name[30];
char number[15];
struct Node* next;
};

struct Node* table[TABLE_SIZE];

void init() {
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = NULL;
}
}

int hash(char* key) {


int sum = 0;
for (int i = 0; i < strlen(key); i++) {
sum += key[i];
}
return sum % TABLE_SIZE;
}

void insert(char* name, char* number) {


int index = hash(name);
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
strcpy(newNode->name, name);
strcpy(newNode->number, number);
newNode->next = NULL;

if (table[index] == NULL) {
table[index] = newNode;
}
else {
struct Node* temp = table[index];
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}

char* search(char* name) {


int index = hash(name);
struct Node* temp = table[index];
while (temp != NULL) {
if (strcmp(temp->name, name) == 0) {
return temp->number;
}
temp = temp->next;
}
return NULL;
}
int main() {
init();
insert("John Smith", "555-555-5555");
insert("Jane Doe", "555-555-5556");
insert("Bob Johnson", "555-555-5557");
char* number = search("Jane Doe");
if (number != NULL) {
printf("Number: %s\n", number);
}
else {
printf("Name not found\n");
}
return 0;
}

You might also like