forked from jhpy1024/CProgrammingLanguageExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise_6-5.c
130 lines (104 loc) · 2.42 KB
/
exercise_6-5.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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define HASH_SIZE 101
struct list
{
char* name;
char* replacement;
struct list* next;
};
static struct list* hash_table[HASH_SIZE];
char* str_duplicate(char* str)
{
char* duplicate = malloc(sizeof(str) + 1);
if (duplicate == NULL)
{
return NULL;
}
strcpy(duplicate, str);
return duplicate;
}
unsigned hash(char* str)
{
unsigned hash_value;
for (hash_value = 0; *str != '\0'; ++str)
{
hash_value = *str + 31 * hash_value;
}
return hash_value % HASH_SIZE;
}
struct list* lookup(char* str)
{
for (struct list* node = hash_table[hash(str)]; node != NULL; node = node->next)
{
if (strcmp(str, node->name) == 0)
{
return node;
}
}
return NULL;
}
struct list* define(char* name, char* replacement)
{
struct list* node;
unsigned hash_value;
if ((node = lookup(name)) == NULL)
{
node = malloc(sizeof(struct list));
if (node == NULL || (node->name = str_duplicate(name)) == NULL)
{
return NULL;
}
hash_value = hash(name);
node->next = hash_table[hash_value];
hash_table[hash_value] = node;
}
else
{
free(node->replacement);
}
if ((node->replacement = str_duplicate(replacement)) == NULL)
{
return NULL;
}
return node;
}
void undefine(char* name)
{
unsigned hash_value = hash(name);
struct list* node = hash_table[hash_value];
if (node == NULL)
{
return;
}
/*
* The first node is the one we need to remove. The for loop below
* won't find this so we have to do it here.
*/
if (strcmp(name, node->name) == 0)
{
hash_table[hash_value] = NULL;
return;
}
for (; node->next != NULL; node = node->next)
{
if (strcmp(name, node->next->name) == 0)
{
node->next = node->next->next;
return;
}
}
}
int main()
{
define("foo", "bar");
define("bar", "baz");
printf("foo %s\n", lookup("foo") == NULL ? "does not exist" : "exists");
printf("bar %s\n", lookup("bar") == NULL ? "does not exist" : "exists");
undefine("foo");
undefine("bar");
printf("foo %s\n", lookup("foo") == NULL ? "does not exist" : "exists");
printf("bar %s\n", lookup("bar") == NULL ? "does not exist" : "exists");
return 0;
}