-
Notifications
You must be signed in to change notification settings - Fork 2
/
symtbl.c
102 lines (94 loc) · 2.35 KB
/
symtbl.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
/*************************************************************************
> File Name: symbol.c
> Author: ellochen
> Mail: [email protected]
> Created Time: Mon May 13 20:01:42 2013
************************************************************************/
//the implement refers to <<Mastering Algorithms with C>>
#include <stdlib.h>
#include <string.h>
#include "symtbl.h"
SymTbl * SYMTBL = NULL;
int symtblInit(int buckets, int (*h)(const void *dat),
int (*match)(const void *dat1, const void *dat2),
void (*destroy)(void *dat))
{
if ((SYMTBL->table = (List *)malloc(buckets * sizeof(List))) == NULL) {
return -1;
}
SYMTBL->buckets = buckets;
for (int i = 0; i < SYMTBL->buckets; ++i) {
listInit(&SYMTBL->table[i], destroy);
}
SYMTBL->h = h;
SYMTBL->match = match;
SYMTBL->destroy = destroy;
SYMTBL->size = 0;
return 0;
}
void symtblDestroy()
{
for (int i = 0; i < SYMTBL->buckets; ++i) {
listDestory(&SYMTBL->table[i]);
}
free(SYMTBL->table);
memset(SYMTBL,0,sizeof(SymTbl));
}
int symtblInsert(const void *data)
{
void *temp = (void *)data;
if (symtblLookup(&temp) == 0) {
return -1;
}
int bucket = SYMTBL->h(data) % SYMTBL->buckets;
int retval = 0;
if ((retval = listInsertNext(&SYMTBL->table[bucket], NULL, data)) == 0) {
SYMTBL->size += 1;
}
return retval;
}
int symtblUpdate(const void *data)
{
int bucket = SYMTBL->h(data) % SYMTBL->buckets;
for (ListElmt *element = listHead(&SYMTBL->table[bucket]);
element != NULL;
element = listNext(element)) {
if (SYMTBL->match(data, listData(element)) == 0) {
memcpy(listData(element), data, sizeof(Symbol));
return 0;
}
}
return -1;
}
int symtblRemove(void **data)
{
int bucket = SYMTBL->h(*data) % SYMTBL->buckets;
ListElmt *prev = NULL;
for (ListElmt *element = listHead(&SYMTBL->table[bucket]);
element != NULL;
element = listNext(element)) {
if (SYMTBL->match(*data, listData(element))) {
if (listRemoveNext(&SYMTBL->table[bucket], prev, data) == 0) {
SYMTBL->size -= 1;
return 0;
}
}else {
return -1;
}
prev = element;
}
return -1;
}
int symtblLookup(void **data)
{
int bucket = SYMTBL->h(*data) % SYMTBL->buckets;
for (ListElmt *element = listHead(&SYMTBL->table[bucket]);
element != NULL;
element = listNext(element)) {
if (SYMTBL->match(*data, listData(element)) == 0) {
*data = listData(element);
return 0;
}
}
return -1;
}