|
その後、先生から回答を貰いました。
解決版のソースを載せてみては?
と、言われたので、先生のをそのまま載せます。
著作権に脅えつつ・・。
このプログラムはみなさんはどう思われますか??
ーーーーーーーーーーーーー
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tr {
char * name;
int hindo;
struct tr *left, *right;
} TREE;
typedef enum { sentou, eisuuzi, kuuhaku, end} KANSU;
int isyoyakugo(char *str){
char *yoyakugo[]={"if","while","switch","for",NULL};
char **p=yoyakugo;
for(p=yoyakugo;*p!=NULL;p++){
if(strcmp(str,*p)==0){
break;
}
}
return *p!=NULL;
}
char* getfunc(){
char buffer[256];
int index=0;
char c;
KANSU status;
status = sentou;
while((status!=end)&&((c=getchar())!=EOF)){
if(index>=256){
fprintf(stderr,"名前が長過ぎます\n");
exit(1);
}
switch(status){
case sentou:
if(isalpha(c)){
index=0;
buffer[index++]=c;
status=eisuuzi;
}
break;
case eisuuzi:
if(c=='('){
buffer[index]='\0';
status=end;
}else if(isalnum(c)){
buffer[index++]=c;
}else if(isspace(c)){
status=kuuhaku;
}else{
status=sentou;
}
break;
case kuuhaku:
if(c=='('){
buffer[index]='\0';
status=end;
}else if(isalpha(c)){
index=0;
buffer[index++]=c;
status=eisuuzi;
}else if(!isspace(c)){
status=sentou;
}
break;
}
}
if(c==EOF){
return NULL;
}
return(strdup(buffer));
}
add(TREE ** tree, char * str){
int res;
if(*tree==NULL){
*tree=(TREE*)malloc(sizeof(TREE));
(*tree)->name=str;
(*tree)->hindo=1;
(*tree)->left=NULL;
(*tree)->right=NULL;
}else{
res=strcmp(str,(*tree)->name);
if(res==0){
(*tree)->hindo++;
}else if(res<0){
add(&((*tree)->left),str);
}else{
add(&((*tree)->right),str);
}
}
}
addbyhindo(TREE **t, TREE *s){
if(*t==NULL){
*t=s;
(*t)->left=NULL;
(*t)->right=NULL;
}else if(s->hindo > (*t)->hindo){
addbyhindo(&((*t)->left),s);
}else if(s->hindo == (*t)->hindo){
if(strcmp(s->name,(*t)->name)<0){
addbyhindo(&((*t)->left),s);
}else{
addbyhindo(&((*t)->right),s);
}
}else{
addbyhindo(&((*t)->right),s);
}
}
sortbyhindo(TREE * s, TREE **t){
if(s!=NULL){
sortbyhindo(s->left,t);
sortbyhindo(s->right,t);
addbyhindo(t,s);
}
}
show(TREE *t){
if(t!=NULL){
show(t->left);
printf("%s: %d\n",t->name,t->hindo);
show(t->right);
}
}
main(){
TREE *t1=NULL, *t2=NULL;
char *func;
while((func=getfunc())!=NULL){
if(!isyoyakugo(func)){
add(&t1,func);
}
}
sortbyhindo(t1,&t2);
show(t2);
}
ーーーーーーーーーーーーーー
|