字典树模板

来源:互联网 发布:莫言 路遥 知乎 编辑:程序博客网 时间:2024/04/29 04:50
我的字典树模板#define MAXNUM 26//定义字典树结构体typedef struct Trie{    bool flag;//从根到此是否为一个单词    Trie *next[MAXNUM];}Trie;//声明一个根Trie *root;//初始化该根void init(){    root = (Trie *)malloc(sizeof(Trie));    root->flag=false;    for(int i=0;i<MAXNUM;i++)    root->next[i]=NULL;}//对该字典树的插入单词操作void insert(char *word){    Trie *tem = root;    while(*word!='\0')    {        if(tem->next[*word-'a']==NULL)        {            Trie *cur = (Trie *)malloc(sizeof(Trie));            for(int i=0;i<MAXNUM;i++)            cur->next[i]=NULL;            cur->flag=false;            tem->next[*word-'a']=cur;        }        tem = tem->next[*word-'a'];        word++;    }    tem->flag=true;}//查询一个单词的操作bool search(char *word){    Trie *tem = root;    for(int i=0;word[i]!='\0';i++)    {        if(tem==NULL||tem->next[word[i]-'a']==NULL)        return false;        tem=tem->next[word[i]-'a'];    }    return tem->flag;}//释放字典树内存操作,由于本题测试数据后程序自动跳出,所以这里没写释放内存函数void del(Trie *cur){    for(int i=0;i<MAXNUM;i++)    {        if(cur->next[i]!=NULL)        del(cur->next[i]);    }    free(cur);}

非常好用的模板,可以使用
原创粉丝点击