/** * Complete the word completion function*/#include<stdio.h>#include<stdlib.h>#include<string.h>#include<errno.h>#include<stdarg.h>#defineMax_child 26#defineError (...) \Logger (stderr, __line__, __va_args__)#defineNotice (...) \Logger (stdout, __line__, __va_args__)/** * Define trie tree nodes*/typedefstructnode_s{intcount; structnode_s *Child[max_child]; Charwords[ -];} node_t;/** * Log*/voidLogger (FILE *FP,intLineConst Char*FMT, ...) {fprintf (FP),"[line]:%d |", line); Va_list ap; Va_start (AP, FMT); vfprintf (FP, FMT, AP); Va_end (AP); fprintf (FP,"\ n");}/** * Create Nodes*/node_t*CreateNode () {node_t*node = (node_t *)calloc(1,sizeof(node_t)); if(node = =NULL) {Error ("CreateNode fail, errno[%d]", errno); }}/** * Add*/intInsert (node_t *root,Char*words) { if(!root | | words[0] ==' /') {error ("insert fail, root or words is null"); return-1; } node_t*node =Root; node_t*tmp; Char*s =words; while(*s! =' /'){ if(Node->child[*s-'a'] ==NULL) {tmp=CreateNode (); if(TMP = =NULL) { Gotoerr; } node->child[*s-'a'] =tmp; } node= Node->child[*s-'a']; S++; } node->count++; memcpy (Node-words, words, strlen (words)); Notice ("Insert success, words =%s", words); return 0; ERR:return-1;}/** * Search for specified words*/intSearch (node_t *root,Char*words) { if(!root | | words[0] ==' /') {error ("search fail, root or words is null"); return-1; } Char*s =words; node_t*node =Root; while(*s! =' /'){ if(Node->child[*s-'a'] ==NULL) { Break; } node= Node->child[*s-'a']; S++; } if(*s = =' /'){ if(Node->count = =0) {printf ("the string was not searched, but it is a prefix of a string \ n"); }Else{printf ("this string was searched, and the number of occurrences was:%d\n", node->count); } searchchild (node); }Else{printf ("no search to this string \ n"); }}/** * The child nodes that are traversed are sorted*/voidSearchchild (node_t *node) { if(!node) {Error ("Searchchild fail, node is null"); return; } inti; if(node->count) {printf ("%s\n", node->words); } for(i =0; i < Max_child; i++){ if(node->Child[i]) {Searchchild (node-Child[i]); } }}/** * Recursive recovery of memory*/voidDel (node_t *root) { if(!root) {Error ("del fail, root is null"); return; } inti; for(i =0; i < Max_child; i++){ if(root->Child[i]) {del (Root-Child[i]); } } Free(root);}intMain () {Char*str ="Jimmy"; node_t*root =CreateNode (); if(!root) { return-1; } //Insert (root, str); //Search (Root, "J");FILE *FP = fopen ("One.txt","R"); if(!p) {Perror ("Open File Fail"); } Charwords[ -]; while(!feof (FP)) {fgets (words,sizeof(words), FP); //Remove carriage return characterWords[strlen (words)-1] =' /'; Insert (root, words); memset (words,0,sizeof(words)); } while(SCANF ("%s", words)) {Search (root, words); } del (root);}
The results are as follows:
Automatic word completion by Trie tree