数据结构 字典树模板

#include "stdio.h" // 字典树模板  hdu 1251
#include "string.h"
#include "stdlib.h"
struct node{
    struct node *next[26];
    int num;
};

struct node *root;

void insert(char *k)
{
    int i;
    struct node *a = root;
    while(k[0]!='\0')
    {
        if(a->next[k[0]-'a'] == NULL)
        {
            node *tt;
            tt = (node *)malloc(sizeof(node));
            tt->num = 1;
            for(i=0;i<26;i++) tt->next[i] = NULL;
            a->next[k[0]-'a'] = tt;
            a = tt;  //移向下一级
        }
        else
        {
            a = a->next[k[0]-'a'];  //移向下一级
            a->num = a->num + 1;
        }
        k++;
    }
}

int find(char *k)
{
    int ans;
    struct node *a = root;
    while(k[0]!='\0')
    {
        if(a->next[k[0]-'a']==NULL)
            return 0;
        else
        {
            ans = a->next[k[0]-'a']->num;
            a = a->next[k[0]-'a'];
        }
        k++;
    }
    return ans;
}

void BFS(node *k);

int main()
{
    int i;
    char str[15];
    root = (node *)malloc(sizeof(node));  //给root指针开辟空间
    for(i=0;i<26;i++)  //root下的指针初始化
        root->next[i] = NULL;
    root->num = 0;
    while(gets(str) && strcmp(str,"")!=0)
        insert(str);
    while(scanf("%s",str)!=-1)
        printf("%d\n",find(str));
    BFS(root);
    return 0;
}

void BFS(node *k)  //深搜去释放内存!
{
    int i;
    if(k==NULL)    return ;
    for(i=0;i<26;i++)
    {
        if(k->next[i]!=NULL)
            BFS(k->next[i]);
    }
    free(k);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值