#define MAX 26 typedef struct Node { struct Node *next[MAX]; int v; }Node, *Trie; Trie root; void createTrie(char *str) { int len, i, j; Node *current, *newnode; len = strlen(str); if(len == 0) { return; } current = root; for(i = 0; i < len; i++) { int id = str[i] - 'a'; if(current->next[id] == NULL) { newnode = (Trie)malloc(sizeof(Node)); newnode->v = 1; //初始v==1 for(j = 0; j < MAX; j++) { newnode->next[j] = NULL; } current->next[id] = newnode; current = current->next[id]; } else { current->next[id]->v++; current = current->next[id]; } } } int findTrie(char *str) { int i, len; Trie current = root; len = strlen(str); if(len == 0) { return 0; } for(i = 0; i < len; i++) { int id = str[i] - 'a'; //根据需要选择是减去'0'还是'a',或者是'A' current = current->next[id]; if(current == NULL) //若为空集,表示不存以此为前缀的串 { return 0; } } return -1; //此串是字符集中某串的前缀 //return current->v; } void dealTrie(Trie T) { int i; if(T == NULL) { return; } for(i = 0; i < MAX; i++) { if(T->next[i] != NULL) { dealTrie(T->next[i]); } } free(T); T = NULL; }
而对于静态建立:
int cnt = 0; Node node[10000]; node[cnt].v = 1; for (int i = 0; i < MAX; i++) { node[cnt].next[i] = NULL; } current->next[id] = &node[cnt++];