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]==' ') { 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]==' ') 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]==' ') 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(" 1. Insert a word "); printf(" 2. Count words"); printf(" 3. Count prefixes"); printf(" 0. Exit "); printf(" Enter your choice: "); scanf("%d",&ch); char input[1000]; switch(ch) { case 1: printf(" Enter a word to insert: "); scanf("%s",input); start=addWord(start,input); break; case 2: printf(" Enter a word to count words: "); scanf("%s",input); printf(" %d",countWords(start,input)); break; case 3: printf(" Enter a word to count prefixes: "); scanf("%s",input); printf(" %d",countPrefix(start,input)); break; } } } int main() { testTrie(); return 0; }