So, I add name and data to a linked list. I need a function to find a specific name.
Ex. find Smith
And using the hash table, I look through to find if smith is one of the names I added.
Currently, my find function doesn't find anything. Once again, I need separate chaining.
Code:
/* prints the first call that matches name */
int find(char* name) {
curr = lookup(name);
if (curr == NULL) return 0;
printf("%s %s\n", curr->list.name, curr->list.number);
return 1;
}
/* string hash function */
int hash(char *s) {
int h = 0;
int i;
for (i = 0 ; s[i] != '\0'; i++) {
s[i] = tolower((char) s[i]);
}
for( ; *s ; s++)
h = *s + h*31;
return h % 13;
}
/* insert hash data */
int insert(char* name, char* number) {
int i = 0;
hNode *hNew = 0;
if ((curr = lookup(name)) == NULL) {
i = hash(name);
hNew = (hNode*) malloc(sizeof(hNode));
hNew->link = curr;
if (hNew->link == NULL) return 0;
strcpy(hNew->link->list.name, name);
if (hNew->link->list.name == NULL) return 0;
hNew->next = hashtab[i];
hashtab[i] = hNew;
}
else
free(curr->list.number);
strcpy(curr->list.number, number);
if(curr->list.number == NULL) return 0;
return 1;
}
/* look up hash value */
Node* lookup(char *s) {
int i = hash(s);
hNode *n = hashtab[i];
for( ; n != NULL ; n = n->next) {
strcpy(hashtab[i]->link->list.name, n->link->list.name);
if (!strcasecmp(n->link->list.name, s)) {
curr = n->link;
return curr;
}
}
return NULL;
}