C语言用二叉树统计一个源文件中每个单词的次数
2012-10-23 11:12
573 查看
由于出现的单词不确定,所以用二叉树实现:
//TreeNode.h typedef struct _TreeNode { int count; //出现的次数 char* word;//单词本身 struct _TreeNode* left; struct _TreeNode* right; }TreeNode; //给TreeNode分配内存 TreeNode* talloc(void) { return (TreeNode*)malloc(sizeof(TreeNode)); } //打印tree void tprint(TreeNode* root) { //打印left->self->right if(root!=NULL) { tprint(root->left); printf("%4d %s\n",root->count,root->word); tprint(root->right); } } //把单词添加节点的合适位置 TreeNode* addNode(TreeNode* node,const char* word) { int con; TreeNode* tmp; if(node==NULL) { node = talloc(); node->count=1; node->word=strdup(word); node->left=node->right=NULL; }else if((con=strcmp(word,node->word))<0) { tmp = addNode(node->left,word); node->left=tmp; }else if(con>0) { tmp = addNode(node->right,word); node->right=tmp; }else{ node->count++; } return node; } /** 从指定的流中读取单词 */ int getWord(char* ch,size_t n,FILE* f) { int c; char* p = ch; while(isspace(c=fgetc(f))) ; if(c!=EOF) *p++=c; if(!isalpha(c)) { *p='\0'; return c; } for(;--n>0;p++) { if(!isalnum(*p=fgetc(f))) { ungetc(*p,f); break; } } *p='\0'; return c; } //是否tree占用的内存 void treeFree(TreeNode* root) { if(root!=NULL) { treeFree(root->left); free(root->word); //释放节点的word占用的内存 free(root); //是否节点占用的内存 treeFree(root->right); } } //Test.c #include <stdio.h> #include <stdlib.h> #include "TreeNode.h" #define MAX 100 int main(int argc, char *argv[]) { FILE* f; char w[MAX]={0}; char* fname="TreeNode.h"; if((f=fopen(fname,"r"))!=NULL) { TreeNode* root = NULL; while((getWord(w,MAX,f)!=EOF)) { if(isalpha(w[0])) root = addNode(root,w); } tprint(root); treeFree(root); fclose(f); }else{ printf("open %s error\n",fname); } getchar(); return 0; }
相关文章推荐
- 一个利用map统计一段英文文章中每个单词出现次数的小程序
- go语言之map练习(二):编写一个程序wordfreq程序,统计输入文本中每个单词出现的频率(次数)
- 用c语言编程 统计输入的一个字符串中每个字母出现的次数
- Java 统计一个字符串中每个单词,或者字母出现的次数
- Java 统计一个字符串中每个单词,或者字母出现的次数
- spark统计文献中每个英文单词出现的次数
- 【c语言】统计一个数字在排序数组中出现的次数
- 初探map()——对一个文件进行统计其中各个单词出现的次数,并按次数从高到低的顺序进行排序
- HashMap分拣存储1:统计每个单词出现的次数
- 有一个string,写一个函数,要求输出这个string中每个单词出现的次数的列表
- 意外收获-ruby编写的一个简单统计单词出现次数的程序
- 统计一个字符串中单词的个数(C语言)
- 一个简单的例子理解C++ map, 运用map统计单词出现的次数
- 读取一个文件中的字符,统计每个字符出现的次数
- 小方法1——CountChar--统计一个字符串中每个字符出现的次数
- 练习 6-4 编写一个程序,根据单词的出现频率按降序打印输入的各个不同单词,并在 每个单词的前面标上它的出现次数
- scala统计一个文件夹下面所有文件的单词出现的总次数
- 编写一个程序,统计给定文件中包含的每个单词出现的频率,并按单词表的顺序显示统计结果
- 【c语言】统计一个数字在排序数组中出现的次数
- HashMap分拣存储2:统计每个单词出现的次数(采用面向对象)