我这里要实现的程序是通过硬编码构造一棵树,然后打印出硬编码树。我从一个结构开始,它包含一个对象名称、一个问题和一个指向同一结构的是或否节点。在主要方法中,我尝试逐步构建结构。但我认为这不是用节点创建树的正确方法。
我的设计描述:这是计算机和用户之间的游戏,计算机提出问题,然后用户回答是或否,计算机将猜测对象。
Start here
|
v
Does it have a tail?
/yes no\
v v
a pangolin Is it flat, round and edible?
/yes no\
v v
a pizza Pete
#include <stdio.h>
#include <stdlib.h>
//object name as key, questions as value
struct node {
char *objectname;// a string declaration to hold an object-name (which may be NULL)
char *question;// a string declaration to hold a question (which may be NULL)
struct node *yes_ptr; // only NULL for objects
struct node *no_ptr; // only NULL for objects
};
typedef struct node thenode;
thenode *objectname = NULL;
thenode *question =NULL;
void nodePrint(struct node *ptr){
if(ptr->objectname == NULL)
{
printf("Object : [NOTHING]" );
printf("Question : %s", ptr->question);
printf("Yes : &s", ptr->yes_ptr);
printf("No : &s", ptr->no_ptr);
}else {
printf("Object : %s", ptr->objectname);
printf("Question : [NOTHING]");
}
}
int main(argc, **argv){
//if ((new_obj = malloc(sizeof(thenode))) == NULL) { abort(); }
thenode a={NULL, "Does it have a tail?", "a pangolin", "pete"};
thenode b={"a pizza",NULL, NULL, NULL};
//thenode c={NULL, "Is it flat, round and edible?", "a pizza", "pete"};
//thenode c={NULL, "Can you dip it in your tea? ", "biscuit", "a pizza"};
struct node *ptr = &thenode;
nodePrint(&a);
nodePrint(&b);
}