标签:malloc ret 相同 roo for 怎么办 trie tree root cpp
/*字典序模板*/
#define MAX 26 //每层有多少种类
typedef struct trie
{
trie *next[MAX];
int v;//一个字典树到此有多少相同前缀的数目
};
trie *root;
void creat_trie(char *str)
{
int len=strlen(str);
trie *p=root,*q;
for(int i=0;i<len;i++)
{
int id=str[i]-‘a‘;
if(p->next[id]==NULL)
{
q=(trie*)malloc(sizeof(trie));
q->v=1;
for(int j=0;j<MAX;j++)
q->next[j]=NULL;
p->next[id]=q;
p=p->next[id];
}
else
{
p->next[id]->v++;
p=p->next[id];
}
}
p->v=-1;
}
int find_trie(char *str)
{
int len=strlen(str);
trie *p=root;
for(int i=0;i<len;i++)
{
int id=str[i]-‘a‘;
p=p->next[id];
if(p==NULL)
return 0;
if(p->v==-1)
return -1;
}
return -1;
}
//超内存怎么办?
//释放空间
void clear_trie(trie *t)
{
if(t==NULL) //空树直接返回
return ;
for(int i=0;i<MAX;i++)
{
if(t->next[i]==NULL)
free(t);
else
clear_trie(t->next[i]);
}
}
标签:malloc ret 相同 roo for 怎么办 trie tree root cpp
原文地址:http://www.cnblogs.com/onlyli/p/7230858.html