-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_map.c
149 lines (101 loc) · 2.66 KB
/
hash_map.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <stdio.h>
#include <stdlib.h>
struct node
{
int hash;
void * value;
struct node * next;
};
struct table
{
int size;
struct node ** list;
};
void insert(struct table * table, char * name, void * value);
struct table * generate_table(int size);
int generate_hash_code(char * name);
void delete_table(struct table * table);
struct table * generate_table(int size)
{
struct table * table = (struct table *) malloc(sizeof(struct table));
table->size = size;
table->list = (struct node **) malloc(sizeof(struct node *)* size);
for(int i = 0; i < size; i++)
{
table->list[i] = NULL;
}
return table;
}
int generate_hash_code(char * name)
{
char current = *name;
int value = 0, index = 0;
while(current != '\0')
{
index++;
value += ((int) current)*index;
current = *(name++);
}
return value;
}
void insert(struct table * table, char * name, void * value)
{
int hash = generate_hash_code(name);
int position = hash % (table->size);
struct node * list = table->list[position];
struct node * new = (struct node *) malloc(sizeof(struct node));
struct node * temp = list;
//Check if node already exists in the list
while(temp != NULL)
{
if(temp->hash==hash)
{
temp->value = value;
return;
}
temp = temp->next;
}
new->hash = hash;
new->value = value;
new->next = list; //add node to the head of the list
table->list[position] = new; //replace old list with new list
}
void * lookup(struct table * table, char * name)
{
int hash = generate_hash_code(name);
int position = hash % (table->size);
struct node * list = table->list[position];
struct node * current = list;
while(current != NULL)
{
if(current->hash == hash) return current->value;
current = current->next;
}
return (int *) -1;
}
void delete_table(struct table * table)
{
for(int i = 0; i < table->size; i++) //for each list in table
{
struct node * list = table->list[i];
struct node * last = NULL;
struct node * current = list;
while(current != NULL)
{
last = current;
current = current->next;
free(last);
}
}
}
//Tests
int main()
{
struct table * table = generate_table(10);
insert(table, (char *) "CAT", (int *) 10);
insert(table, (char *) "DOG", (int *) 20);
insert(table, (char *) "FISH", (int *) 30);
char * str = "DOG";
printf("%s = %d \n", str, (int *) lookup(table, str));
delete_table(table);
}