Exemple #1
0
int main(){
int n;
printf("\nEnter the number of strings you want to add: ");
scanf("%d",&n);
int i;
char data[100];
TNode* root=NULL;
for(i=0;i<n;i++){
//printf("\nEnter the length of string you want to add : ");
printf("\nEnter the string you want to add : ");
scanf("%s",data);
InsertTrie(&root,data);
}
printf("\%d words added ",n);
getch();

printf("\nEnter the string you want to search : ");
scanf("%s",data);
int result=SearchTrie(root,data);
if(result){
printf("\nWord found !Hurray!");
}else{
printf("\nSorry! word not found !");
}
char* buffer=(char*)malloc(sizeof(char)*100);
printf("\nPress enter to print all the words in the dictionary you just created :\n");
getch();
PrintAll(root,buffer,0);
getch();
return 0;
}
//Inserting str in the trie, it creates the trie nodes needed to insert the string, str
void InsertTrie(struct Trie_Node **node, char *str) {

    if(str[0] == '\0')
        return;

    if(*node == NULL) {
        *node = (struct Trie_Node *)malloc(sizeof(struct Trie_Node));
        InitialiseTrieNode(node, str[0]);
    }

    if(str[1] == '\0') {
        (*node)->is_word = 1;
        return;
    }

    InsertTrie(&((*node)->children[str[1]-'a']), &str[1]);
    return;
}
//Builds the trie by inserting all words in the trie. All upper case aplhabets are converted to lower case before inserting.
void BuildTrie(char *dictionary) {

    FILE *fp;
    char word[25];
    int i = 1;
    fp = fopen(dictionary, "r");
    word[0] = '$';

    while(fscanf(fp,"%s",&word[1]) != EOF) {
        i = 1;
        while(word[i] != '\0') {
            if(word[i] >= 'A' && word[i] <= 'Z')
                word[i] = word[i] + 32;
            i++;
        }
        InsertTrie(&root, word);
    }

    fclose(fp);
}
Exemple #4
0
void main()
{
  TrieTree t;
  int i;
  char s[MAXKEYLEN+1];
  KeysType k;
  Record *p;
  Record r[N]={{{"CAI"},1},{{"CAO"},2},{{"LI"},3},{{"LAN"},4},
               {{"CHA"},5},{{"CHANG"},6},{{"WEN"},7},{{"CHAO"},8},
               {{"YUN"},9},{{"YANG"},10},{{"LONG"},11},{{"WANG"},12},
               {{"ZHAO"},13},{{"LIU"},14},{{"WU"},15},{{"CHEN"},16}};
  /* 数据元素(以教科书式9-24为例) */
  InitDSTable(&t);
  for(i=0;i<N;i++)
  {
    r[i].key.num=strlen(r[i].key.ch)+1;
    r[i].key.ch[r[i].key.num]=Nil; /* 在关键字符串最后加结束符 */
    p=SearchTrie(t,r[i].key);
    if(!p)
      InsertTrie(&t,&r[i]);
  }
  printf("按关键字符串的顺序遍历Trie树(键树):\n");
  TraverseDSTable(t,pr);
  printf("\n请输入待查找记录的关键字符串: ");
  scanf("%s",s);
  k.num=strlen(s)+1;
  strcpy(k.ch,s);
  k.ch[k.num]=Nil; /* 在关键字符串最后加结束符 */
  p=SearchTrie(t,k);
  if(p)
    pr(p);
  else
    printf("没找到");
  printf("\n");
  DestroyDSTable(&t);
}