我只是有一个关于制作二叉树的问题,因为这段代码不起作用,它会将节点放置在它们不应该去的地方,尽管它不会像管道破裂一样崩溃它的泄漏内存。这个想法是一个简单的猜谜游戏,它只是试图猜测你在想什么,当它猜错时,你输入一个问题和答案来帮助它学习。相关代码:
我想我的主要问题是 char *guess 有时只会存储传递给 getnew() 的原始字符串的片段。接下来是 traverse() 中的逻辑,因为无论用户输入如何,它都会跳转到“否”条件。
struct binary {
unsigned long ID;
char *guess;
char isAns;
struct binary *yes;
struct binary *no;
};
typedef struct binary Node;
void traverse(Node **top)
{
if(*top)
{
char ans[128] = "ok";
char ans2[128] = "ok";
if((*top)->isAns=='y')
{
fprintf(stdout,"Is it %s (y/n)? ",(*top)->guess);
}
else
{
fprintf(stdout,"%s (y/n)? ",(*top)->guess);
}
while(!fgets(ans,128,stdin));
if((*top)->isAns=='y')
{
if(ans=="y")
{
printf("Successful string of guesses!\n");
}
else
{
printf("Enter another question to figure out the difference: ");
while(!fgets(ans,128,stdin));
Node *q=getnew(ans,'n');
printf("Enter the right answer: ");
while(!fgets(ans2,128,stdin));
push1(top,q,'n');
(*top)->yes = getnew(ans2,'y');
}
}
else
{
if(ans=="y")
{
if((*top)->yes)
{
traverse(&(*top)->yes);
}
else
{
printf("Null node for top->yes\n");
printf("Enter an answer: ");
while(!fgets(ans,128,stdin));
(*top)->yes=getnew(ans,'y');
}
}
else
{
if((*top)->no)
{
traverse(&(*top)->no);
}
else
{
printf("Null node for top->no\n");
printf("Enter an answer: ");
while(!fgets(ans,128,stdin));
(*top)->no=getnew(ans,'y');
}
}
}
}
else
{
char ques[128] = "ok";
char ans[128] = "ok";
printf("Node is null\n");
printf("Put in a question and answer to yes condition\n");
printf("Enter question: ");
while(!fgets(ques,128,stdin));
printf("Enter answer for yes condition: ");
while(!fgets(ans,128,stdin));
(*top) = getnew(ques,'n');
(*top)->yes=getnew(ans,'y');
}
printf("\n\n");
}
Node * getnew(char *msg, char isAns)
{
Node *nnew = malloc(sizeof(Node));
nnew->ID=clock();
nnew->guess=malloc(sizeof(msg));
strcpy(nnew->guess,msg);
nnew->isAns=isAns;
nnew->yes=0;
nnew->no=0;
return nnew;
}
我很感激任何帮助。