一个简单的Trie树实现

header file

#ifndef TRIE_H_INCLUDED
#define TRIE_H_INCLUDED

#include<stdio.h>
#include<malloc.h>

typedef struct trie
{
    int words;
    int prefixes;
    struct trie *edges[26];
} trie;

trie * initialize(trie *node);
trie * addWord(trie *ver,char *str);
int countWords(trie *ver,char *str);
int countPrefix(trie *ver,char *str);

#endif // TRIE_H_INCLUDED

source file

#include "trie.h"

trie * initialize(trie *node)
{
    if(node==NULL)
    {
        node=(trie *)malloc(sizeof(trie));
        node->words=0;
        node->prefixes=0;
        int i;
        for(i=0; i<26; i++)
            node->edges[i]=NULL;
        return node;
    }

}

trie * addWord(trie *ver,char *str)
{
    printf("%d --- %c  ",ver->words, str[0]);
    if(str[0]=='\0')
    {
        ver->words=ver->words+1;
    }
    else
    {

        ver->prefixes=(ver->prefixes)+1;
        char k;
        k=str[0];
        str++;
        int index=k-'a';
        if(ver->edges[index]==NULL)
        {
            ver->edges[index]=initialize(ver->edges[index]);
        }

        ver->edges[index]=addWord(ver->edges[index],str);
    }
    return ver;
}

int countWords(trie *ver,char *str)
{
    if(str[0]=='\0')
        return ver->words;
    else
    {
        int k=str[0]-'a';
        str++;
        if(ver->edges[k]==NULL)
            return 0;
        return countWords(ver->edges[k],str);
    }
}

int countPrefix(trie *ver,char *str)
{
    if(str[0]=='\0')
        return ver->prefixes;
    else
    {
        int k=str[0]-'a';
        str++;
        if(ver->edges[k]==NULL)
            return 0;
        return countPrefix(ver->edges[k],str);
    }
}

test file


#include<stdio.h>
#include<malloc.h>
#include "trie.h"

void testTrie()
{
    trie *start=NULL;
    start=initialize(start);
    int ch=1;
    while(ch)
    {

        printf("\n 1. Insert a word ");
        printf("\n 2. Count words");
        printf("\n 3. Count prefixes");
        printf("\n 0. Exit\n");
        printf("\nEnter your choice: ");
        scanf("%d",&ch);
        char input[1000];
        switch(ch)
        {
        case 1:
            printf("\nEnter a word to insert: ");
            scanf("%s",input);
            start=addWord(start,input);
            break;
        case 2:
            printf("\nEnter a word to count words: ");
            scanf("%s",input);
            printf("\n%d",countWords(start,input));
            break;
        case 3:
            printf("\nEnter a word to count prefixes: ");
            scanf("%s",input);
            printf("\n%d",countPrefix(start,input));
            break;
        }
    }
}

int main()
{
    testTrie();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值