2008—7 单词词频

计算一行字符中单词的词频
其中计算词频用二叉树计算
2008年最后一题(有几个注意点)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct BTnode
{
	//char *ch;
	char ch[20];
	int count;
	struct BTnode *lchild,*rchild;
}BTnode;

void insert(BTnode **p,char *s)
{
	if((*p)==NULL)
	{
		(*p)=(BTnode*)malloc(sizeof(BTnode));
		(*p)->lchild=(*p)->rchild=NULL;
		strcpy((*p)->ch,s);
		(*p)->count=1;
	}
	else
	{
		if(strcmp(s,(*p)->ch)==0)
			(*p)->count++;
		else if(strcmp(s,(*p)->ch)>0)
			insert(&((*p)->rchild),s);
		else
			insert(&((*p)->lchild),s);
	}
}

void getresult(BTnode *p,int word)
{
	if(p!=NULL)
	{
		printf("%s的频度为%f\n",p->ch,(1.0)*p->count/word);
		getresult(p->lchild,word);
		getresult(p->rchild,word);
	}
}

int main()
{
	int i=0,j=0,word=0;
	char s[200],temp[10];
	BTnode *p=NULL;
	gets(s);
	while(s[i-1]!='\0')
	{
		if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z'))
			temp[j++]=s[i++];
		else
		{
			temp[j]='\0';  //修改
			insert(&p,temp);
			j=0;
			temp[j]='\0'; //修改
			i++;          //修改
			word++;
		}
	}
	getresult(p,word);
	system("pause");
	return 0;
}

//l am li lei and l come from china still lei and from gg and 输入

注意注意注意!!!

本题有个大坑:
通过指针调用字符串的时候不能使用strcpy复制,必须用字符数组(主程序中结构体注释掉了),因为strcpy的原来类型中有个const。比如下面的程序,换程注释的就不行执行

#include<stdio.h>
#include<string.h>
int main()
{
	//char *s=NULL;
	char s[200];
	char *a="abc";
	strcpy(s,a);
	puts(s);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值