#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct Nameval Nameval;
struct Nameval{
char *name;
int value;
Nameval *left;/*lesser*/
Nameval *right;/*greater*/
};
Nameval *newitem(char *name,int value);
Nameval *insert(Nameval *treep,Nameval *newp);
Nameval *lookup(Nameval *treep,char *name);
void applyinorder(Nameval *treep,void (*fn)(Nameval *,void *),void *arg);
void printnv(Nameval *treep,void *arg);
int main()
{
Nameval *tree=NULL,*p;
char *name;
int i,value;
for(i=1;i<=5;i++)
{
name=(char *)malloc(10*sizeof(char));
if(!name)return -1;
printf("please insert name and value:/n");
scanf("%s",name); //注意这里输入
scanf("%d",&value);
p=newitem(name,value);
tree=insert(tree,p);
}
printf("---------------------------/n");
applyinorder(tree,printnv,"%s: %d/n");
printf("---------------------------/n");
}
Nameval *newitem(char *name,int value)
{
Nameval *newp;
newp=(Nameval *)malloc(sizeof(Nameval));
if(!newp)
return NULL;
newp->name=name;
newp->value=value;
newp->left=NULL;
newp->right=NULL;
return newp;
}
/* insert: insert newp in treep ,return treep */
Nameval *insert(Nameval *treep,Nameval *newp)
{
int cmp;
if(treep==NULL)
return newp;
cmp=strcmp(newp->name,treep->name);
if(cmp==0)
printf("warning:insert: duplicate entry %s ignored",newp->name);
else if(cmp<0)
treep->left=insert(treep->left,newp);
else
treep->right=insert(treep->right,newp);
return treep;
}
/* lookup: look up name in tree treep */
Nameval *lookup(Nameval *treep,char *name)
{
int cmp;
if(treep==NULL)
return NULL;
cmp=strcmp(name,treep->name);
if(cmp==0)
return treep;
else if(cmp<0)
return lookup(treep->left,name);
else
return lookup(treep->right,name);
}
/* applyinorder: inorder application of fn to treep */
void applyinorder(Nameval *treep,void (*fn)(Nameval *,void *),void *arg)
{
if(treep==NULL)
return;
applyinorder(treep->left,fn,arg);
(*fn)(treep,arg);
applyinorder(treep->right,fn,arg);
}
/* applypostorder: postorder application of fn to treep */
void applypostorder(Nameval *treep,void (*fn)(Nameval *,void *),void *arg)
{
if(treep==NULL)
return;
applyinorder(treep->left,fn,arg);
applyinorder(treep->right,fn,arg);
(*fn)(treep,arg);
}
/* printnv: print name and value using format in arg*/
void printnv(Nameval *treep,void *arg)
{
char *fmt;
fmt=(char *)arg;
printf(fmt,treep->name,treep->value);
}