-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash-operations.c
129 lines (107 loc) · 2.54 KB
/
hash-operations.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
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include "hash.h"
bool insert(char *value)
{
// Make a new node and copy the word inside it
node *NewNode = malloc(sizeof(node));
if (NewNode == NULL)
{
return false;
}
strcpy(NewNode->word, value);
NewNode->next = NULL;
// Calculate the hash key
// Key is the same whether the first character is upper case or lower case
unsigned int Key;
Key = hash(value);
// Check if chain[key] is empty
if (table[Key] == NULL)
{
table[Key] = NewNode;
}
// Collision
else
{
// Those two lines must be in order, otherwise you lose your chain
NewNode->next = table[Key];
table[Key] = NewNode;
}
return true;
}
bool check(const char *word)
{
unsigned int Key;
Key = hash(word);
node *temp = table[Key];
// Calculate the length of the word that needs to be searched in the hash table
while (temp)
{
if (strcasecmp(word, temp->word) == 0)
{
// The word matches the data
return true;
}
temp = temp->next;
}
// Otherwise
return false;
}
bool update(const char *word, const char *new_word)
{
unsigned int Key;
Key = hash(word);
node *temp = table[Key];
// Calculate the length of the word that needs to be searched in the hash table
while (temp)
{
if (strcasecmp(word, temp->word) == 0)
{
// The word matches the data
strcpy(temp->word, new_word);
return true;
}
temp = temp->next;
}
// Otherwise
return false;
}
bool delete(const char *word)
{
unsigned int Key;
Key = hash(word);
node *temp = table[Key];
// Calculate the length of the word that needs to be searched in the hash table
while (temp)
{
if (strcasecmp(word, temp->word) == 0)
{
// The word matches the data
strcpy(temp->word, "");
return true;
}
temp = temp->next;
}
// Otherwise
return false;
}
bool unload(void)
{
node *FreeNode;
for (int i = 0; i < Number; i++)
{
// Free list, by using a while loop and a temporary variable to point
// to the next node before freeing the current one
while (table[i] != NULL)
{
FreeNode = table[i]->next;
free(table[i]);
table[i] = FreeNode;
}
}
return true;
}