C语言 二叉树,一个猜动物的小游戏

1. 此项目用到的知识点: 二叉树, struct, 文件读写。

2. 其中最复杂的地方是:复制一个指针的内容,参考:https://stackoverflow.com/questions/39938648/copy-one-pointer-content-to-another

1. 头文件 "node_utils.h"


#define BOOL int
#define TRUE 1
#define FALSE 0//This is the NODE type definition.
//The field question_or_animal contains
//either an animal name if the node is a leaf
//or a question used to descend into the tree.
//The left child represents the node to descend
//to if the answer to the question is "yes", the
//right child represents the node to descend to
//if the answer is "no".typedef struct node {char question_or_animal[200];struct node *left;struct node *right;
} NODE;//This reads a line from the standard input.
//It returns true if a line was actually read.
//It returns false if end-of-file was encountered
//before any data could be read.BOOL read_line(char *p);//Recursively performs a pre-order traversal of the
//tree starting at node p, printing the question_or_animal field to
//the file specified by the file pointer.void write_tree(NODE *p, FILE *f);//Reads the file specified by the file pointer and 
//creates a tree based on the contents of the file.
//Returns a pointer to the root node of the tree.NODE *read_tree(FILE *f);

2. 二叉树节点相关的函数  node_utils.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "node_utils.h"#define BOOL int
#define TRUE 1
#define FALSE 0BOOL read_line(char *p)
{char c = getchar();if (c == EOF)return FALSE;while ((c == '\n') || (c == ' ') || (c == '\t')) //ignore leading whitespacec = getchar();while (c != '\n') {*p++ = c;c = getchar();}*p = 0;return TRUE;
}void write_tree(NODE *p, FILE *f)
{if (p == NULL)fprintf(f,"NULL\n");else {fprintf(f,"%s\n", p->question_or_animal);write_tree(p->left,f);write_tree(p->right,f);}
}NODE *read_tree(FILE *f)
{char s[200];int i;NODE *n;char c;//attempt to read the first character of the linec = getc(f);//if end-of-file has been reached, then it means//that the input wasn't structured correctly.if (c == EOF) {printf("Error: Wrong number of entries in file\n");exit(1);}i = 0;for(i=0; (c != EOF) && (c != '\n'); i++) {s[i] = c;c = getc(f);}s[i] = 0;if(!strcmp(s,"NULL"))return NULL;n = (NODE *) malloc(sizeof(NODE));strcpy(n->question_or_animal, s);n->left = read_tree(f);n->right = read_tree(f);return n;
}

3. 主函数  animals.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "node_utils.h"#define BOOL int
#define TRUE 1
#define FALSE 0NODE *root = NULL;BOOL yes_response() {char response[10];while (TRUE) {fgets(response, 11, stdin);response[strcspn(response, "\n")] = 0;  // remove leading newlineif (strcasecmp(response, "yes") == 0) {return TRUE;} else if (strcasecmp(response, "y") == 0) {return TRUE;} else if (strcasecmp(response, "no") == 0) {return FALSE;} else if (strcasecmp(response, "n") == 0) {return FALSE;} else {printf("You answered neither yes nor no!\n");}}
}NODE *new_node(char *s) {NODE *newNode = (NODE *) malloc(sizeof(NODE));char *s2;s2 = malloc(sizeof(char) * (strlen(s) + 1));strcpy(s2, s);strcpy(newNode->question_or_animal, s2);newNode->left = NULL;newNode->right = NULL;free(s2);return newNode;
}void guess_animal() {if (!root) {printf("What animal were you thinking of? > ");char *animal_name;fgets(animal_name, 200, stdin);animal_name[strcspn(animal_name, "\n")] = 0;  // remove leading newlineroot = new_node(animal_name);} else {NODE *current_node = new_node(root->question_or_animal);*current_node = *root;while (current_node->left && current_node->right) {printf("%s (yes/no) > ", current_node->question_or_animal);if (yes_response()) {current_node = current_node->left;} else {current_node = current_node->right;}}printf("I'm guessing: %s\n", current_node->question_or_animal);printf("Am I right? >");if (yes_response()) {printf("I win ! \n");return;}// ask 3 questionsprintf("\noops.   What animal were you thinking of? > ");char new_animal_name[200];fgets(new_animal_name, 200, stdin);new_animal_name[strcspn(new_animal_name, "\n")] = 0;  // remove leading newlineprintf("Enter a yes/no question to distinguish a %s and a %s > ", new_animal_name,current_node->question_or_animal);char new_question[200];fgets(new_question, 200, stdin);new_question[strcspn(new_question, "\n")] = 0;  // remove leading newlineprintf("What is the answer of a %s (yes or no) > ", new_animal_name);BOOL yes_no_to_new_question = yes_response();// create 2 nodeschar *new_animal_name_ptr = new_animal_name;NODE *newAnimalNode = new_node(new_animal_name_ptr);     // yesNODE *oldAnimalNode = new_node(current_node->question_or_animal);// set relationschar *question;question = malloc(sizeof(char) * (strlen(new_question) + 1));strcpy(question, new_question);strcpy(current_node->question_or_animal, question);if (yes_no_to_new_question) {current_node->left = newAnimalNode;current_node->right = oldAnimalNode;} else {current_node->left = oldAnimalNode;current_node->right = newAnimalNode;}if (root->left && root->right) {if (yes_no_to_new_question) {root->left = current_node;} else {root->right = current_node;}} else {*root = *current_node;}free(question);}
}//This code is complete. Just add comments where indicated.int main() {int i;BOOL done = FALSE;//insert comment here: read a data file "data.dat", assign to a pointerFILE *datafile = fopen("data.dat", "r");if (datafile == NULL) {printf("data.dat not found\n");exit(1);}//insert comment here: read the backup file.FILE *backupfile = fopen("data.dat.bak", "w");//insert comment here: find the root of a binary treeroot = read_tree(datafile);//call write_tree() to write the initial tree to the//backup file (i.e. to back up the tree data)write_tree(root, backupfile);//close both files (for now)fclose(backupfile);fclose(datafile);printf("Welcome to the animal guessing game (like 20 questions).\n");do {printf("\nThink of an animal...\n");guess_animal();  // insert comment here: run the main gameprintf("\nDo you want to play again? (yes/no) >");} while (yes_response());  // keep ask user input if the response always is yes//now open the "data.dat" file for writingdatafile = fopen("data.dat", "w");//insert comment:// call write_tree() to write the full binary tree to a data file (data.dat).// this will overwrite the original content.write_tree(root, datafile);//close the data.dat filefclose(datafile);
}

编译命令:

# 编译此项目

gcc -o A1 animals.c node_utils.c

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/47679.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

进程的地址空间

一、写个代码见一见地址空间 1、问题 在代码中我们在第五秒时会在子进程中改变全局变量 g_val 但是我们发现了一个奇怪的现象&#xff1a;在子进程中改变 g_val &#xff0c;由于进程的独立性&#xff0c;所以子进程和父进程的值不一样是可以理解的&#xff0c;但是为什么变量…

20240718每日后端------------kafka VS RabbitMQ:选择正确的消息代理

目标 消息队列选型 Kafka VS RabbitMQ Kafka Apache Kafka 是一个开源分布式事件流平台&#xff0c;以其高吞吐量、容错性和实时数据处理能力而闻名。 Kafka 遵循发布-订阅模型&#xff0c;生产者将消息写入主题&#xff0c;消费者订阅这些主题以接收消息。 Kafka 将消息存储…

【C++11】线程

本篇文章更多的是熟悉一下C11的线程库接口&#xff0c;与linux的相关线程接口是非常相似的&#xff0c;更多的是将面向过程改为了面向对象。 并没有一些概念的讲解。 想知道线程的相关概念的可以看一看这篇文章及后续 在C11之前&#xff0c;涉及到多线程问题&#xff0c;都是和…

访问控制系列

目录 一、基本概念 1.客体与主体 2.引用监控器与引用验证机制 3.安全策略与安全模型 4.安全内核 5.可信计算基 二、访问矩阵 三、访问控制策略 1.主体属性 2.客体属性 3.授权者组成 4.访问控制粒度 5.主体、客体状态 6.历史记录和上下文环境 7.数据内容 8.决策…

使用TableConvert API将CSV转换为JSON数组

TableConvert API 是一款多功能工具&#xff0c;旨在简化不同数据格式之间的转换过程。通过访问370种不同的转换器&#xff0c;该API可以在包括CSV、Excel、HTML、JSON、Markdown等多种文件类型和结构之间实现无缝数据转换。 为什么选择TableConvert的CSV到JSON数组API&#x…

面试问题:react的Reconciler(调度器)为什么在做异步可中断不用原生Generator,自己做了一个Fiber

首先Generator也是有异步中断功能的但是能他是有传染性的&#xff0c;使用了Generator则需要上下文的其他函数也需要做主改变&#xff0c;这样心智负担比较重&#xff0c;就比如说我定义一个Generator方法&#xff0c;里面有ABC三个函数我分别在B的前面和C的前面放一个yield打断…

Linux: network: device事件注册机制 chatGPT; notify

ChatGPT 在 Linux 内核中,有关网络设备(net-device)的事件注册机制,允许用户在网络设备的状态发生变化(例如设备被删除、添加或修改)时接收通知。这主要通过 netdev 事件通知机制实现。具体来说,内核提供了一组用于注册和处理网络设备事件的 API。 以下是一些关键组件…

memcached 高性能内存对象缓存

memcached 高性能内存对象缓存 memcache是一款开源的高性能分布式内存对象缓存系统&#xff0c;常用于做大型动态web服务器的中间件缓存。 mamcached做web服务的中间缓存示意图 当web服务器接收到请求需要处理动态页面元素时&#xff0c;通常要去数据库调用数据&#xff0c;但…

【快速逆向一/无过程/有源码】《大学》在线投稿系统

逆向日期&#xff1a;2024.07.18 使用工具&#xff1a;Node.js 加密工具&#xff1a;Crypto-js标准库 文章全程已做去敏处理&#xff01;&#xff01;&#xff01; 【需要做的可联系我】 【点赞 收藏 关注 】仅供学习&#xff0c;仅供学习&#xff0c; 本文为快速逆向&#x…

如果制作红星照耀中国思维导图?6个软件帮助你快速制作思维导图

如果制作红星照耀中国思维导图&#xff1f;6个软件帮助你快速制作思维导图 制作《红星照耀中国》思维导图可以帮助更好地理解和梳理书中的重要信息和内容。以下是六款推荐的思维导图软件及其特点和使用方法&#xff0c;帮助你快速制作高质量的思维导图。 迅捷画图 特点与功…

Milvus核心组件(2)---- etcd 详解

目录 背景 etcd 简介 1. 基本概念 2. 数据存储特性 3. KVS的操作 4. 租约(Lease)机制 5. 实际应用场景 Milvus 下的 etcd 服务及存储结构 etcd 服务 端口 存储位置 安全连接信息 嵌入式方式运行 etcd 文件存储结构 解析etcd 文件 连接 etcd server 注意事项…

n2. Web相关知识和工具

Web相关知识和工具 1. http协议相关基础知识2. http协议状态码3. Web相关工具2.1 links2.2 wget2.3 curl2.4 httpie 4. httpd的压力测试工具 1. http协议相关基础知识 URI&#xff1a; Uniform Resource Identifier 统一资源标识&#xff0c;分为URL 和 URN URN&#xff1a;U…

Python基础语法篇(下)+ 数据可视化

Python基础语法&#xff08;下&#xff09; 数据可视化 一、函数&#xff08;一&#xff09;函数的定义&#xff08;二&#xff09;函数的调用和传参 二、文件操作&#xff08;一&#xff09;文件读取和写入&#xff08;二&#xff09;文件对象及方法&#xff08;三&#xff09…

【数学建模】——【线性规划】及其在资源优化中的应用

目录 线性规划问题的两类主要应用&#xff1a; 线性规划的数学模型的三要素&#xff1a; 线性规划的一般步骤&#xff1a; 例1&#xff1a; 人数选择 例2 &#xff1a;任务分配问题 例3: 饮食问题 线性规划模型 线性规划的模型一般可表示为 线性规划的模型标准型&…

达梦数据库的系统视图v$sqltext

达梦数据库的系统视图v$sqltext 在达梦数据库&#xff08;DM Database&#xff09;中&#xff0c;V$SQLTEXT 是一个系统视图&#xff0c;用于显示当前正在执行或最近执行的SQL语句的文本信息。这个视图对于监控和分析数据库中的SQL活动非常有用&#xff0c;尤其是在需要调试性…

【MySQL篇】Percona XtraBackup工具备份指南:常用备份命令详解与实践(第二篇,总共五篇)

&#x1f4ab;《博主介绍》&#xff1a;✨又是一天没白过&#xff0c;我是奈斯&#xff0c;DBA一名✨ &#x1f4ab;《擅长领域》&#xff1a;✌️擅长Oracle、MySQL、SQLserver、阿里云AnalyticDB for MySQL(分布式数据仓库)、Linux&#xff0c;也在扩展大数据方向的知识面✌️…

银河麒麟搭建ftp服务器

1.先 查看系统架构&#xff0c;我常遇到的一般银河麒麟是arrch64的 lscpu uname -a cat /etc/os-release 去下载对应版本的vsftp.rpm包和ftp包 Index of /NS/ (cs2c.com.cn) 1.安装rpm rpm -ivh *.rpm --nodeps --force #强制安装 2.修改配置文件 vi /etc/vsftpd/vsftpd.co…

Qt Android Native Error: JNI DETECTED ERROR IN APPLICATION: java_object == null

开发的qt android程序在低版本上运行正常&#xff0c;在高版本上启动时崩溃&#xff0c;报如下错误 W java.lang.RuntimeException: Cant create handler inside thread Thread[qtMainLoopThread,5,main] that has not called Looper.prepare()at android.os.Handler.<ini…

如何使用Python调用颜值评分接口

引言 在当今社会&#xff0c;人工智能技术被应用于各个领域&#xff0c;包括图像识别和分析。今天&#xff0c;我们将利用Python来调用小思框架颜值评分接口&#xff0c;该接口可以接收一张人脸图片&#xff0c;并返回一个表示颜值水平的分数。 接口功能与参数 方法URL参数描…

PiT : 基于池化层Pooling layer的Vision Transformer

CNN的降维原理;随着深度的增加,传统CNN的通道维数增加,空间维数减少。经验表明,这样的空间降维对变压器结构也是有益的,并在原有的ViT模型的基础上提出了一种新的基于池的视觉变压器(PiT)。 1. 引言 ViT与卷积神经网络(CNN)有很大的不同。将输入图像分成1616小块馈送到变压…