開発環境
- OS: Windows 10 Pro
- IDE(統合開発環境): Visual Studio 2017 (Clang/C2(試験的))
- プログラミング言語: C(Visual C)
Head First C ―頭とからだで覚えるCの基本 (David Griffiths (著)、Dawn Griffiths (著)、中田 秀基 (監修)、木下 哲也 (翻訳)、オライリージャパン)の6章(データ構造と動的メモリ - 架け橋を築く)、大きな疑問(p. 305)を取り組んでみる。
大きな疑問(p. 305)
コード
#include <stdlib.h> // system
#include <stdio.h>
#include <string.h>
typedef struct Node
{
char *question;
struct Node *no;
struct Node *yes;
} Node;
bool yes_no(char *question)
{
char answer[3];
printf("%s? (y/n): ", question);
fgets(answer, 3, stdin);
return answer[0] == 'y';
}
Node *node_new(char *question)
{
Node *n = (Node *)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 = node_new("question1");
start_node->no = node_new("person1");
start_node->yes = node_new("person2");
Node *current;
do
{
current = start_node;
for (;;)
{
if (yes_no(current->question))
{
/* */
}
else if (current->no)
{
current = current->no;
}
else
{
printf("容疑者は? ");
fgets(suspect, 20, stdin);
Node *yes_node = node_new(suspect);
current->yes = yes_node;
Node *no_node = node_new(current->question);
current->no = no_node;
printf("%s, %s? ", suspect, current->question);
fgets(question, 80, stdin);
/* 置き換える前に解放 */
free(current->question);
current->question = _strdup(question);
break;
}
}
} while (yes_no("??"));
release(start_node);
system("pause");
return 0;
}
入出力結果(コマンドプロンプト)
question1? (y/n): n person1? (y/n): n 容疑者は? person3 person3 , person1? question2 ??? (y/n): n 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿