forked from embedded2015/phonebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phonebook_opt.c
75 lines (65 loc) · 1.55 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "phonebook_opt.h"
entry *findhash(char lastName[], hashtable *ht)
{
int index = hash(lastName);
entry *target = ht->list[index];
if(ht->list[index]==NULL)
return NULL;
while(strcasecmp(lastName, target->lastName) == 0) {
target = target->pNext;
}
return target;
}
void appendhash(char lastName[], hashtable *ht, pool *mem_pool)
{
int index = hash(lastName);
entry *temp;
temp = mem_allocate(mem_pool);
strcpy(temp->lastName, lastName);
temp->pNext = ht->list[index];
ht->list[index]=temp;
}
hashtable *Create_Hash_Table()
{
hashtable *ht;
ht = (hashtable *)malloc(sizeof(hashtable));
ht->list = (entry **)malloc(sizeof(entry *)*TABLE_SIZE);
for(int i=0; i<TABLE_SIZE; i++)
ht->list[i]=NULL;
return ht;
}
int hash(char lastName[])
{
int i=0, sum=0;
while(lastName[i] != '\0') {
sum = sum*3 + lastName[i];
i++;
}
return sum % TABLE_SIZE;//Choose a prime to multiple the sum.
}
void create_pool(pool *mem_pool)
{
mem_pool->start = (entry *) malloc(sizeof(entry)*350000);
mem_pool->now = mem_pool->start;
mem_pool->end = mem_pool->start + 350000;
}
entry *mem_allocate(pool *mem_pool)
{
if(mem_pool->end == mem_pool->now)
return NULL;
mem_pool->now += 1;
return (entry *)(mem_pool->now - 1);
}
void *mem_free(pool *mem_pool)
{
mem_pool->now -= 1;
return NULL;
}
void destroy_pool(pool *mem_pool)
{
free(mem_pool->start);
free(mem_pool);
}