[求助]生成一棵二叉树问题

yes152 2007-08-22 10:49:25
大家帮我看看,程序那错了呢?怎么不能动态输入呢?编译通过了,可是,当我输入一个单词之后,回车,再输入单词,狂吃我内存呢?好郁闷呀!我用的VC++6.0
//生成一棵二叉树,比较单词出现的次数
//c++ java Fortran basic Foxbase
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXWORD 20
struct tnode{
char *word; //指向一个单词
int count; //访问次数
struct tnode *left; //左孩子
struct tnode *right; //右孩子
};
char *GetWord() //读取单词
{
char *p;
if((p=(char*)malloc(MAXWORD+1))==NULL) {printf("Out of memory!\n");return(NULL);}
scanf("%MAXWORDs",p);
if(strlen(p)==0) return(NULL);
return p;
}
struct tnode *tree(struct tnode *p,char *w) //生成树
{
struct tnode *talloc();
int cond;
if(p==NULL)
{
p=talloc();
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=tree(p->left,w);
else
p->right=tree(p->right,w);
return(p);
}
void treeprint(struct tnode *point) //打印树
{
if(point!=NULL)
{
treeprint(point->left);
printf("%4d%s\n",point->count,point->word);
treeprint(point->right);
}
}
struct tnode *talloc()
{
return((struct tnode*)malloc(sizeof(struct tnode)));
}
int main()
{
struct tnode *root;
char *t=NULL;
root=NULL;
while((t=GetWord())!=NULL)
root=tree(root,t);
treeprint(root);
return 0;
}
...全文
133 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
yes152 2007-08-24
  • 打赏
  • 举报
回复
MAXWORD去掉了
这次更糟糕了,又不能输入变成无限输入了,怎么输入也不出结果呢?
求助前辈帮我看看。
非完美主义者 2007-08-23
  • 打赏
  • 举报
回复
scanf("%MAXWORDs",p);这个有问题,格式字符串里,MAXWORD是不能展开为20的。

69,381

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧