-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_search.c
75 lines (61 loc) · 1.3 KB
/
hash_search.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASHSIZE 101
struct nlist {
struct nlist *next;
char *name;
char *defn;
};
static struct nlist *hashtab[HASHSIZE];
unsigned hash(char *s)
{
unsigned hashval;
for (hashval = 0; *s != '\0'; ++s) {
hashval = *s + 31 * hashval;
}
return hashval % HASHSIZE;
}
struct nlist *lookup(char *s)
{
struct nlist *np;
for (np = hashtab[hash(s)]; np != NULL; np = np->next) {
if (strcmp(np->name, s) == 0) {
return np;
}
}
return NULL;
}
struct nlist *install(char *name, char *defn)
{
struct nlist *np;
unsigned hashval;
if ((np = lookup(name)) == NULL) {
np = (struct nlist *) malloc(sizeof(*np));
if (np == NULL || (np->name = strdup(name)) == NULL)
return NULL;
hashval = hash(name);
np->next = hashtab[hashval];
hashtab[hashval] = np;
}
else {
free(np->defn);
}
if ((np->defn = strdup(defn)) == NULL)
return NULL;
return np;
}
int main()
{
struct nlist *result;
install("Apoorva", "Anand");
install("Computer", "Science");
result = lookup("Apoorva");
printf("%s\n", result->defn);
result = lookup("Computer");
printf("%s\n", result->defn);
result = lookup("Not found");
if (result == NULL)
printf("As expected it was not found\n");
return 0;
}