现在已经完成代码,可以读取文件中的单词,使其按字典序列输出,如何将其改成按单词出现频率由高至低输出
代码如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
struct tnode{
char word[MAX];
int count;
struct tnode *left,*right;
};
struct tnode *treewords(struct tnode *,char *);
void treeprint(struct tnode *);
int main()
{
char word[MAX];
FILE *bfp;
char c;
int i;
struct tnode *root;
root=NULL;
bfp=fopen("article.txt","r");
while((c=fgetc(bfp))!=EOF){
ungetc(c,bfp);
for(i=0;(c=fgetc(bfp))!=' '&&c!='\n'&&c!=EOF;i++){
if((c>='A'&&c<='Z')||(c>='a'&&c<='z')){
c=tolower(c);
word[i]=c;
}else
break;
}
word[i]='\0';
if(strlen(word)>0)
root=treewords(root,word);
}
treeprint(root);
return 0;
}
struct tnode *treewords(struct tnode *p,char *w)
{
int cond;
if(p==NULL){
p=(struct tnode*)malloc(sizeof(struct tnode));
strcpy(p->word,w);
p->count=1;
p->left=p->right=NULL;
}
else if((cond=strcmp(w,p->word))==0){
p->count++;
}
else if(cond<0){
p->left=treewords(p->left,w);
}
else
p->right=treewords(p->right,w);
return (p);
}
void treeprint(struct tnode *p)
{
if(p!=NULL){
treeprint(p->left);
printf("%s %d\n",p->word,p->count);
treeprint(p->right);
}
}
可以用c++的hash实现,更简单些。
将所有节点的指针放在一个数组里面(需要知道单词的个数,然后遍历二叉树获得这个数组)
使用任何一种排序方法根据词频排序
使用后根序遍历二叉树,在遍历过程中,把每个节点动态排序,生成一个链表(按词频率插入)