|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 16
#define UNIT 4
#define MAXLEN 256
int ending=0 ;
typedef struct TrieNode
{
int count;
int isleaf;
struct TrieNode *child[MAX];
}Tree,*Tree_r; //结构体指针数组
int totalleafs = 0;
int totaldepth = 0;
int totalnodes = 0;
Tree * trieCreate() //建立树根节点
{
Tree * node = (Tree *)malloc(sizeof(Tree));
if(!node)
ending = 1 ;
memset(node, 0, sizeof(Tree));
return node;
}
unsigned char getbytes(unsigned char c,int index,int unit)
{
unsigned char u[]={0b00000000,0b00000001};
if (8 % unit != 0)
return -1;
int k = 8 - (index+1) * unit;
c = c >> k;
return c & u[unit];
}
void f_insert(Tree_r obj, char * strx) //建立完整tire树
{
Tree * t = obj;
char * p = strx;
int d =0;
while(*p != '\0')
{
unsigned char c = *p; //汉字可以看成两个字母的二进制组合,加上128,用这个数作数组下标
for(int j = 0; j < 8/UNIT; j++)
{
d=1;
unsigned char i = getbytes(c,j,UNIT);
if(t->child[i]==NULL) //子节点为空 ,则建立新的节点,并指向此节点
{
Tree *temp = trieCreate() ;
temp->isleaf = 1;
if(t->isleaf != 1)
{
totaldepth += d;
totalleafs++;
}
}
else
{
t = t->child[i];
}
}
p++;
t->count++ ; // 记录字典中字符串到达的位置及个数
}
}
int f_search(Tree_r obj, char * strx)
{
Tree *t = obj;
char *p = strx;
int count = 0;
while(*p != '\0')
{
unsigned char c = *p; //汉字可以看成两个字母的二进制组合,加上128,用这个数作数组下标
for(int j = 0; j < 8/UNIT; j++)
{
unsigned char i = getbytes(c,j,UNIT);
if(t->child[i] != NULL)
{
t = t->child[i];
count++;
}
else
{
return 0;
}
}
}
if(t->count != 0)
return 1;
else
return 0;
}
void f_free(Tree* obj) //释放内存
{
if(!obj) return;
for(int i=0;i<2; i++)
{
if(obj->child[i]!=NULL)
f_free(obj->child[i]);
}
free(obj);
}
int main()
{
int i,j,l ;
char str[300] ; //换MAXLEN
FILE *fpr1,*fpr2,*fpw ;
fpr1 = NULL ;
fpr2 = NULL ;
fpw = NULL ;
Tree_r root = NULL ; //申明一个指向Trie树的指针
root = trieCreate() ; //建立根节点,使指针指向这个区域
if(ending)
{
printf("Error!\n");
return 7 ;
}
if(root==NULL)
printf("Fail!\n");
if((fpr1=fopen("C:\\Users\\tulin\\dict.txt", "r")) == NULL)
{
printf("File can not be opened.\n");
return 1;
}
if((fpr2=fopen("C:\\Users\\tulin\\words.txt", "r")) == NULL)
{
printf("File can not be opened.\n");
return 1;
}
do
{
if(fscanf(fpr1,"%s",str) != EOF) //fscanf返回值 EOF
{
f_insert(root , str);
totalnodes++;
if(ending)
{
printf("Error.\n");
return 7 ;
}
}
}while(!feof(fpr1));
fpw = fopen("result1.txt", "w+");
do
{
if(fscanf(fpr2,"%s",str) != EOF)
{
j = f_search(root , str);
if(j == 1)
{
fprintf(fpw,"%s yes\n",str);
}
else if(j == 0)
{
fprintf(fpw,"%s no\n",str);
}
else
{
printf("Error.\n");
return 0 ;
}
}
}while(!feof(fpr2));
printf("Success\n");
printf("Average depth: %f\n", (float)totaldepth / totalnodes);
printf("Total depth: %f\n", (float)totaldepth );
fclose(fpr1);
fclose(fpr2);
fclose(fpw);
f_free(root);
return 0 ;
}
为什么这个代码只输出no,查找不到yes的字符啊,救救孩子吧,小学期要交作业了 |
|