今天做了下Trie树,虽然不难,但是还是费了一些功夫。
先上代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//节点结构
typedef struct tNode{
char c;
struct tNode *next[26];
long num;
}tNode;
//树结构
typedef struct tTree{
tNode *head;
}tTree;
//产生节点
tNode* createNode()
{
tNode *t = (tNode*)malloc(sizeof(tNode));
if(!t)
{
printf("create node malloc wrong!");
return NULL;
}
t->c = 0;
int i = 0;
for(; i<26; ++i)
{
t->next[i] = NULL;
}
t->num = 0;
return t;
}
//产生树
tTree* createTree()
{
tTree *t = (tTree*)malloc(sizeof(tTree));
if(!t)
{
printf("create malloc wrong!");
return NULL;
}
t->head = createNode();
return t;
}
//加入一个单词
long addWord(char *word, tTree *tree)
{
if(!word) return -1;
tNode *temp = tree->head;
int i = 0;
while(word[i] != '\0')
{
if(temp->next[word[i]-'a'])
{
temp=temp->next[word[i]-'a'];
temp->num += 2;
i++;
}
else
{
tNode *newNode = createNode();
newNode->c = word[i] - 'a';
newNode->num += 2;
temp->next[word[i]-'a'] = newNode;
temp = newNode;
i++;
}
}
if(temp->num % 2 ==0) temp->num += 1;
return temp->num >>1;
}
//查找前缀包含的个数
long countNum(char *pre, tTree *tree)
{
if(!pre) return -1;
tNode *temp = tree->head;
int i = 0;
while(pre[i] != '\0')
{
if(temp->next[pre[i]-'a'])
{
temp = temp->next[pre[i]-'a'];
++i;
}
else
return 0;
}
return temp->num>>1;
}
//清理堆上申请的树
void delTree(tNode *&subT)
{
int i = 0;
for(; i<26; ++i)
{
if(subT->next[i])
{
delTree(subT->next[i]);
}
}
free(subT);
}
int main()
{
long n = 0, m = 0;
scanf("%ld",&n);
getchar();
char str[11];
tTree *tree = createTree();
long i = 0;
while(i<n)
{
scanf("%s",str); ++i;
addWord(str,tree);
memset(str, 0, sizeof(str));
}
scanf("%ld",&m);
getchar();
i = 0;
while(i<m)
{
scanf("%s",str); ++i;
long cNum = countNum(str,tree);
printf("%ld\n",cNum);
memset(str, 0, sizeof(str));
}
printf("\n");
delTree(tree->head);
//scanf("%d",&i);
return 0;
}
写代码的过程中有点磕绊,在debug时也分析了一些原因,总结如下:
1.数据结构设计一定要注意。本次的节点和树的数据结构有些冗余,一个节点结构充分了,这是在写之前没有仔细考虑的。本次设计的注意点:存储信息有哪些? 以什么方式存储? 能不能少用一点内存?
2.递归与迭代过程中,一定要注意单次的变量更新。(bug从这里出的比较多)
3..函数设计过程中,要对返回情况做讨论。(尤其是在调用函数时,仔细考虑可能的返回值以及对当前结果的影响)。