-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.c
89 lines (73 loc) · 1.7 KB
/
table.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
#include <stdio.h>
#include "hash.h"
typedef struct tableElem_t *tableElem;
struct H_hashTable_t {
tableElem *table;
int size;
};
struct tableElem_t {
void *data;
char *key;
tableElem next;
};
int hash(char *key, int size);
tableElem TableElem(void *data, char *key, tableElem next);
void H_insert(H_hashTable h, char *key, void *data)
{
int hashval = hash(key, h->size);
h->table[hashval] = TableElem((void *)data, key, h->table[hashval]);
}
void *H_find(H_hashTable h, char *key)
{
tableElem tmp = h->table[hash(key,h->size)];
while (tmp && strcmp(key, tmp->key) != 0)
tmp = tmp->next;
if (tmp == NULL)
return (NULL);
return (tmp->data);
}
void H_delete(H_hashTable h, char *key)
{
int index;
tableElem tmp;
index = hash(key, h->size);
if (h->table[index] != NULL)
{
if (strcmp(h->table[index]->key, key) == 0)
h->table[index] = h->table[index]->next; /* Memory Leak */
else
{
for(tmp = h->table[index]; tmp->next != NULL &&
strcmp(tmp->next->key, key) != 0; tmp = tmp->next);
if (tmp->next)
tmp->next = tmp->next->next;
}
}
}
int hash(char *key, int size)
{
unsigned int hashval = 0;
int retval;
for ( ; key[0]; key++)
hashval = (hashval << 5) + key[0];
retval = hashval % size;
return (retval);
}
H_hashTable H_HashTable(int size)
{
int i;
H_hashTable retval = (H_hashTable) malloc(sizeof(*retval));
retval->size = size;
retval->table = malloc_checked(size * sizeof(tableElem *));
for (i = 0; i < size; i++)
retval->table[i] = NULL;
return (retval);
}
tableElem TableElem(void *data, char *key, tableElem next)
{
tableElem retval = malloc_checked(sizeof(*retval));
retval->data = data;
retval->key = key;
retval->next = next;
return (retval);
}