字典樹C語言實現
阿新 • • 發佈:2018-12-31
-
-
字典樹
-
-
#include <stdio.h> #include <stdlib.h>
#define MAX 26 typedef struct TrieNode { int nCount; // 該節點字首 出現的次數 struct TrieNode *next[MAX]; //該節點的後續節點 } TrieNode; TrieNode Memory[1000000]; int allocp = 0; //初始化一個節點。 TrieNode * createTrieNode() { TrieNode * tmp = &Memory[allocp++]; tmp->nCount = 1; for (int i = 0; i < MAX; i++) tmp->next[i] = NULL; return tmp; } void insertTrie(TrieNode * * pRoot, char * str) { TrieNode * tmp = *pRoot; int i = 0, k; while (str[i]) { k = str[i] - 'a'; if (tmp->next[k]) { tmp->next[k]->nCount++; } else { tmp->next[k] = createTrieNode(); } tmp = tmp->next[k]; i++; } } int searchTrie(TrieNode * root, char * str) { if (root == NULL) return 0; TrieNode * tmp = root; int i = 0, k; while (str[i]) { k = str[i] - 'a'; if (tmp->next[k]) { tmp = tmp->next[k]; } else return 0; i++; } return tmp->nCount; } int main(void) { char s[11]; TrieNode *Root = createTrieNode(); while (gets(s) && s[0] != '0') //讀入0 結束 { insertTrie(&Root, s); } while (gets(s)) //查詢輸入的字串 { printf("%d\n", searchTrie(Root, s)); } return 0; }