forked from embedded2015/phonebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phonebook_opt.c
61 lines (47 loc) · 1.26 KB
/
phonebook_opt.c
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
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "phonebook_opt.h"
hashTable *initHashTable(tableSize htsize)
{
hashTable *ht = NULL;
int i;
if ((ht = (hashTable *) malloc(sizeof(hashTable))) == NULL)
return NULL;
if ((ht->hashEntry = (entry **) malloc(sizeof(entry*)*htsize)) == NULL)
return NULL;
for (i = 0; i < htsize; i++) {
ht->hashEntry[i] = NULL;
}
ht->htsize = htsize;
return ht;
}
size_t hash(char *lastName, hashTable *ht)
{
size_t hash_val = 0;
while (*lastName != '\0')
hash_val += *lastName++;
return hash_val % ht->htsize;
}
entry *findName(char lastName[], hashTable *ht)
{
entry *tmp;
size_t hashIndex = hash( lastName, ht);
for (tmp = ht->hashEntry[hashIndex]; tmp != NULL; tmp = tmp->pNext) {
if (strcmp(lastName, tmp->lastName) == 0) {
return tmp;
}
}
return NULL;
}
entry *append(char lastName[], hashTable *ht)
{
size_t hashIndex = hash(lastName, ht);
entry *newEntry;
if ((newEntry = (entry *) malloc(sizeof(entry))) == NULL)
return NULL;
strcpy(newEntry->lastName, lastName);
newEntry->pNext = ht->hashEntry[hashIndex];
ht->hashEntry[hashIndex] = newEntry;
return newEntry;
}