Commit d74431cd5970e3a29d2fdbf1908a9d9c9a14e3cd
1 parent
d4da0378
Ajout de tree.c
Showing
2 changed files
with
96 additions
and
0 deletions
Show diff stats
... | ... | @@ -0,0 +1,91 @@ |
1 | +#include <stdio.h> | |
2 | +#include <stdlib.h> | |
3 | +#include <stdbool.h> | |
4 | +#define MAX 30 | |
5 | + | |
6 | +typedef struct node* Node; | |
7 | + | |
8 | +typedef struct node { | |
9 | + char letter; | |
10 | + Node next[26]; | |
11 | + bool endWord; | |
12 | +}node; | |
13 | + | |
14 | +void mk_empty_tree(Node* Tree) | |
15 | +{ | |
16 | + *Tree = NULL; | |
17 | +} | |
18 | + | |
19 | +bool is_empty_tree(Node* Tree) | |
20 | +{ | |
21 | + return(*Tree==NULL); | |
22 | +} | |
23 | + | |
24 | +void init_tree(Node* Tree) | |
25 | +{ | |
26 | + if(is_empty_tree(Tree)) | |
27 | + { | |
28 | + *Tree = malloc(sizeof(Node)); | |
29 | + (*Tree)->letter = '?'; | |
30 | + (* Tree)->endWord = false; | |
31 | + for(int i=0; i<26; i++) | |
32 | + (*Tree)->next[i] = NULL; | |
33 | + } | |
34 | +} | |
35 | + | |
36 | +void add_in_tree(Node *Tree, char word[]) | |
37 | +{ | |
38 | + char letter = word[0]; | |
39 | + int j=0; | |
40 | + while(letter != '/0') | |
41 | + { | |
42 | + char letter = word[j]; | |
43 | + if((*Tree)->next[letter-'a']!=NULL) | |
44 | + *Tree = (*Tree)->next[letter-'a']; | |
45 | + else | |
46 | + { | |
47 | + Node new = NULL; | |
48 | + new = malloc(sizeof(Node)); | |
49 | + new->letter = letter; | |
50 | + for(int i=0; i<26; i++) | |
51 | + { | |
52 | + new->next[i]=NULL; | |
53 | + } | |
54 | + (*Tree)->next[letter-'a'] = new; | |
55 | + } | |
56 | + j++; | |
57 | + } | |
58 | + (*Tree)->endWord = true; | |
59 | +} | |
60 | + | |
61 | +void read_lib(FILE* fp, Node* Tree) | |
62 | +{ | |
63 | + char word[MAX]; | |
64 | + while(1) | |
65 | + { | |
66 | + if(fscanf(fp, "%s", &word)!=1) | |
67 | + break; | |
68 | + add_in_tree(Tree, word); | |
69 | + } | |
70 | +} | |
71 | + | |
72 | +void print_tree(Node Tree, int index) | |
73 | +{ | |
74 | + Node printedTree = Tree; | |
75 | + if(printedTree!=NULL) | |
76 | + printf("%c", printedTree->letter); | |
77 | + if(printedTree->next[index]==NULL) | |
78 | + print_tree(printedTree, index+1); | |
79 | + else | |
80 | + print_tree(printedTree->next[index], 0); | |
81 | +} | |
82 | + | |
83 | +int main(int argc, char *argv[]) | |
84 | +{ | |
85 | + Node Tree = NULL; | |
86 | + FILE* fp; | |
87 | + fp = fopen(argv[argc-1], "r"); | |
88 | + read_lib(fp, &Tree); | |
89 | + print_tree(Tree, 0); | |
90 | + return 0; | |
91 | +} | ... | ... |