#include<stdio.h>#include<stdlib.h>#include<string.h>#define TREE_WIDTH 256#define WORDLENMAX 128structtrie_node_st{intcount;intpass;//add a count for the part-include for example 'this is' then the 'is' is hited two times structtrie_node_st*next[TREE_WIDTH];};staticstructtrie_node_stroot={0,0,{NULL}};staticconstchar*spaces=" \t\n/.\"\'()";voidmyfree(structtrie_node_st*rt){for(inti=0;i<TREE_WIDTH;i++){if(rt->next[i]!=NULL){myfree(rt->next[i]);rt->next[i]=NULL;}}free(rt);return;}staticintinsert(constchar*word){inti;structtrie_node_st*curr,*newnode;if(word[0]=='\0'){return0;}curr=&root;for(i=0;;++i){if(word[i]=='\0'){break;}curr->pass++;//countif(curr->next[word[i]]==NULL){newnode=(structtrie_node_st*)malloc(sizeof(structtrie_node_st));memset(newnode,0,sizeof(structtrie_node_st));curr->next[word[i]]=newnode;}curr=curr->next[word[i]];}curr->count++;return0;}staticvoidprintword(constchar*str,intn){printf("%s\t%d\n",str,n);}staticintdo_travel(structtrie_node_st*rootp){staticcharworddump[WORDLENMAX+1];staticintpos=0;inti;if(rootp==NULL){return0;}if(rootp->count){worddump[pos]='\0';printword(worddump,rootp->count+rootp->pass);}for(i=0;i<TREE_WIDTH;++i){worddump[pos++]=i;do_travel(rootp->next[i]);pos--;}return0;}intmain(void){char*linebuf=NULL,*line,*word;size_tbufsize=0;intret;while(1){ret=getline(&linebuf,&bufsize,stdin);if(ret==-1){break;}line=linebuf;while(1){word=strsep(&line,spaces);if(word==NULL){break;}if(word[0]=='\0'){continue;}insert(word);}}do_travel(&root);free(linebuf);for(inti=0;i<TREE_WIDTH;i++){if(root.next[i]!=NULL){myfree(root.next[i]);}}exit(0);}
参考资料
^ 1.01.1Black, Paul E. trie. Dictionary of Algorithms and Data Structures. 国家标准技术研究所. 2009-11-16 [2012-07-08]. (原始内容存档于2010-05-19).
^Knuth, Donald. 6.3: Digital Searching. The Art of Computer Programming Volume 3: Sorting and Searching 2nd. Addison-Wesley. 1997: 492. ISBN 0-201-89685-0.