/
hashset.c
106 lines (84 loc) · 2.55 KB
/
hashset.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
#include "hashset.h"
struct HashSet *createHashSet(int numberBuckets, string_hash_func hashFunc)
{
struct HashSet *newHashSet;
int index;
newHashSet = (struct HashSet *)malloc(sizeof(struct HashSet));
if (newHashSet == NULL) {
fprintf(stderr, "HashSet allocation error!\n");
exit(-1);
}
newHashSet->numberBuckets = numberBuckets;
newHashSet->hashFunc = hashFunc;
newHashSet->buckets = (struct List **)
malloc(numberBuckets * sizeof(struct List *));
if (newHashSet->buckets == NULL) {
fprintf(stderr, "HashSet buckets allocation error!\n");
exit(-1);
}
for (index = 0; index < numberBuckets; index++)
newHashSet->buckets[index] = createList();
return newHashSet;
}
void deleteHashSet(struct HashSet *hashset)
{
int index;
for (index = 0; index < hashset->numberBuckets; index++)
deleteList(hashset->buckets[index]);
free(hashset->buckets);
free(hashset);
}
void addElementToHashset(struct HashSet *hashset, const char *word)
{
unsigned int code;
code = hashset->hashFunc(word, hashset->numberBuckets);
addElementToList(hashset->buckets[code], word);
}
void removeElementFromHashset(struct HashSet *hashset, const char *word)
{
unsigned int code;
code = hashset->hashFunc(word, hashset->numberBuckets);
removeElementFromList(hashset->buckets[code], word);
}
int isElementInHashset(struct HashSet *hashset, const char *word)
{
unsigned int code;
code = hashset->hashFunc(word, hashset->numberBuckets);
return isElementInList(hashset->buckets[code], word);
}
void printBucket(struct HashSet *hashset, int bucketNumber, FILE *file)
{
struct ListNode *current;
if (hashset->buckets[bucketNumber]->numberElements == 0)
return;
current = hashset->buckets[bucketNumber]->start;
while (current != NULL) {
fprintf((file != NULL) ? file : stdout, "%s ", current->word);
current = current->next;
}
fprintf((file != NULL) ? file : stdout, "\n");
}
void printHashset(struct HashSet *hashset, FILE *file)
{
int bucketNumber;
for (bucketNumber = 0; bucketNumber < hashset->numberBuckets;
bucketNumber++)
printBucket(hashset, bucketNumber, file);
}
struct HashSet *resizeHashset(struct HashSet *hashset, int newSize)
{
struct HashSet *newHashSet;
struct ListNode *current;
int bucketNumber;
newHashSet = createHashSet(newSize, hashset->hashFunc);
for (bucketNumber = 0; bucketNumber < hashset->numberBuckets;
bucketNumber++) {
current = hashset->buckets[bucketNumber]->start;
while (current != NULL) {
addElementToHashset(newHashSet, current->word);
current = current->next;
}
}
deleteHashSet(hashset);
return newHashSet;
}