-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrie.c
78 lines (70 loc) · 1.17 KB
/
trie.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
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <malloc.h>
#include <stdbool.h>
#include <assert.h>
#define ALPHA 26
#define MAX 1000
char data[MAX][ALPHA];
struct node
{
bool leaf;
struct node *c[ALPHA];
};
typedef struct node *trie;
trie newNode()
{
trie go = (trie)malloc(sizeof(struct node));
int i;
go->leaf = false;
for(i = 0; i < ALPHA; ++i)
{
go->c[i] = NULL;
}
return go;
}
void insert(trie strt, const char *s)
{
int len = strlen(s), i, idx;
trie go = strt;
for(i = 0; i < len; ++i)
{
idx = s[i] - 'a';
if (go->c[idx] == NULL)
{
go->c[idx] = newNode();
}
go = go->c[idx];
}
go->leaf = true;
}
bool search(trie strt, const char *s)
{
int len = strlen(s), i, idx;
trie go = strt;
for(i = 0; i < len; ++i)
{
idx = s[i] - 'a';
if (go->c[idx] == NULL)
{
return false;
}
go = go->c[idx];
}
return (go != NULL && go->leaf);
}
void initaliseTrie(char *filename)
{
FILE *fp = fopen(filename, "r");
trie strt = newNode();
//ignore name of files
fscanf(fp, "%s", data[0]);
fscanf(fp, "%s", data[0]);
for(int i = 0; i < MAX; ++i)
{
fscanf(fp, "%s", data[i]);
insert(strt, data[i]);
}
fclose(fp);
}