/* 《嗨翻C语言》随书练习 6章 2016-12-06 xiousheng@126.com 二叉树例子,警务罪犯判断档案系统,哈哈 书中可以专家系统例子 */ #include <stdio.h> #include <stdlib.h> //要动态用内存必须用这个库 malloc(),free() #include <string.h> typedef struct node{ char * question; //嫌疑人 struct node *no; struct node *yes; }node; //简单的判断函数 int yes_no(char * question){ char answer[3]; printf("%s?(y/n):", question); fgets(answer, 3, stdin); return answer[0] == 'y'; }; node * create(char *question){ //创建 node *n = malloc(sizeof(node)); n ->question = strdup(question); n ->no = NULL; n ->yes = NULL; return n; } //释放内存 void release(node *n){ if (n){ if (n->no) release(n->no); if (n->yes)release(n->yes); if (n->question) free(n->question); free(n); } }; int main(){ char question[80]; char suspect[20]; node *start_node = create("嫌疑犯有胡子吗"); start_node ->no = create("王小华"); start_node ->yes = create("猪猪赌"); node *current; do { current = start_node; while (1){ if (yes_no(current->question)){ if (current->yes){ current = current->yes; }else{ printf("%s是犯罪嫌疑人\r\n",current->question); break; } }else if(current->no){ current = current->no; }else{ /*新的犯罪嫌疑人*/ printf("谁是新的犯罪嫌疑人?"); fgets(suspect, 20, stdin); suspect[strlen(suspect)-1] = '\0' ; //去掉换行符号 node *yes_node = create(suspect); current->yes = yes_node; /*把以前的排除了的嫌疑人全加到不是这边*/ node *no_node = create(current->question); current->no = no_node; /*记录新的特征*/ printf("%s是犯罪嫌疑人,%s不是。\r\n请输入辨认他的信息:", suspect, current->question); fgets(question, 80, stdin); question[strlen(question)-1] = '\0' ; //去掉换行符号 free(current->question ) ; current->question = strdup(question); break; } } } while (yes_no("再次运行")); release(start_node); return 0; };
结果配图