#include <stdio.h>
#include <malloc.h>
#define MAX 26
typedef struct __trie{
struct __trie* nodes[MAX];
char c;
char count;
void* payload;
struct __trie* parent;
} Trie;
Trie* trie_new_node(void* payload)
{
Trie* p = (Trie*)malloc(sizeof(Trie));
if(NULL == p)
{
return NULL;
}
int i = 0;
for(/* void */;i<MAX;i++)
{
p->nodes[i] = NULL;
}
p->c = 0;
p->count = 0;
p->payload = payload;
p->parent = NULL;
return p;
}
int trie_insert(Trie* t,char* str,void* payload)
{
char c = *str;
if(c == 0)
{
t->payload = payload;
t->count = 1;
return 0;
}
if(c > 'z' || c < 'a')
{
return -1;
}
int index = c - 'a';
if(t->nodes[index] == NULL)
{
t->nodes[index] = trie_new_node(NULL);
t->nodes[index]->c = c;
t->nodes[index]->parent = t;
}
return trie_insert(t->nodes[index],++str,payload);
}
int trie_update(Trie* t,char* str,void* payload)
{
return trie_insert(t,str,payload);
}
Trie* trie_find(Trie* t,char* str)
{
if(*str == 0){
if(t->count == 1)
{
return t;
}
return NULL;
}
int index = *str - 'a';
if(t->nodes[index] == NULL)
{
return NULL;
}
return trie_find(t->nodes[index],++str);
}
void trie_delete(Trie* t,char* str){
if(*str == 0){
t->count = 0;
return ;
}
int index = *str - 'a';
Trie* node = t->nodes[index];
if(node == NULL)
{
return ;
}
trie_delete(node,++str);
int del = 1;
int i;
for(i=0;i<MAX;i++){
if(node->nodes[i] != NULL){
del = 0;
break;
}
}
if(del == 1 && node->count == 0){
node->parent->nodes[node->c-'a'] = NULL;
free(node);
}
}
void trie_list(Trie* t,void(*handle)(void*)){
if(t->count != 0){
handle(t->payload);
}
int i=0;
for(/*void*/;i<MAX;i++)
{
if(t->nodes[i] != NULL){
printf("not empty\n");
trie_list(t->nodes[i],handle);
}
}
}
int main(void)
{
Trie* root = trie_new_node(NULL);
trie_insert(root,"a","a\n");
trie_insert(root,"abc","abc\n");
trie_insert(root,"abcd","abcd\n");
trie_list(root,printf);
printf("\n\n\n\n\n");
trie_delete(root,"abcd");
trie_delete(root,"a");
trie_list(root,printf);
return 0;
}