trie字典树简单实现

#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;
}

转载于:https://my.oschina.net/u/3025685/blog/815897

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值