Blame view

tree.c 1.52 KB
d74431cd   grouille   Ajout de tree.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
  #include <stdio.h>
  #include <stdlib.h>
  #include <stdbool.h>
  #define MAX 30
  
  typedef struct node* Node;
  
  typedef struct node {
    char letter;
    Node next[26];
    bool endWord;
  }node;
  
  void mk_empty_tree(Node* Tree)
  {
    *Tree = NULL;
  }
  
  bool is_empty_tree(Node* Tree)
  {
    return(*Tree==NULL);
  }
  
  void init_tree(Node* Tree)
  {
    if(is_empty_tree(Tree))
      {
        *Tree = malloc(sizeof(Node));
        (*Tree)->letter = '?';
        (* Tree)->endWord = false;
        for(int i=0; i<26; i++)
  	(*Tree)->next[i] = NULL;
      }
  }
  
  void add_in_tree(Node *Tree, char word[])
  {
    char letter = word[0];
    int j=0;
    while(letter != '/0')
      {
        char letter = word[j];
        if((*Tree)->next[letter-'a']!=NULL)
  	*Tree = (*Tree)->next[letter-'a'];
        else
  	{
  	  Node new = NULL;
  	  new = malloc(sizeof(Node));
  	  new->letter = letter;
  	  for(int i=0; i<26; i++)
  	    {
  	      new->next[i]=NULL;
  	    }
  	  (*Tree)->next[letter-'a'] = new;
  	}
        j++;
      }
    (*Tree)->endWord = true;
  }
  
  void read_lib(FILE* fp, Node* Tree)
  {
    char word[MAX];
    while(1)
      {
        if(fscanf(fp, "%s", &word)!=1)
  	break;
        add_in_tree(Tree, word);
      }
  }
  
  void print_tree(Node Tree, int index)
  {
    Node printedTree = Tree;
    if(printedTree!=NULL)
      printf("%c", printedTree->letter);
    if(printedTree->next[index]==NULL)
      print_tree(printedTree, index+1);
    else
      print_tree(printedTree->next[index], 0);
  }
  
  int main(int argc, char *argv[])
  {
    Node Tree = NULL;
    FILE* fp;
    fp = fopen(argv[argc-1], "r");
    read_lib(fp, &Tree);
    print_tree(Tree, 0);
    return 0;
  }