From cb3c69cf90bb1ab4ce708d0a44e63a7cbead3a40 Mon Sep 17 00:00:00 2001 From: mk570rp Date: Thu, 16 Apr 2026 15:44:42 +0000 Subject: [PATCH] du5 --- du5/program.c | 82 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 58 insertions(+), 24 deletions(-) diff --git a/du5/program.c b/du5/program.c index 943242b..ba166f1 100644 --- a/du5/program.c +++ b/du5/program.c @@ -11,24 +11,31 @@ typedef struct Tree { struct Tree *no; } Tree; +// читання дерева Tree* readTree() { char line[SIZE]; - if (!fgets(line, SIZE, stdin)) return NULL; + if (fgets(line, SIZE, stdin) == NULL) return NULL; + line[strcspn(line, "\r\n")] = 0; + if (line[0] == '\0') return NULL; + Tree *node = malloc(sizeof(Tree)); node->yes = NULL; node->no = NULL; if (line[0] == '*') { node->isAnswer = 1; + int i = 1; while (line[i] == ' ') i++; + strcpy(node->text, line + i); } else { node->isAnswer = 0; strcpy(node->text, line); + node->yes = readTree(); node->no = readTree(); } @@ -36,38 +43,59 @@ Tree* readTree() { return node; } -int count(Tree *n) { - if (!n) return 0; - if (n->isAnswer) return 1; - return count(n->yes) + count(n->no); +// перевірка пустого рядка +int EmptyLine() { + char line[SIZE]; + + if (fgets(line, SIZE, stdin) == NULL) return 0; + + return (strcmp(line, "\n") == 0); } -void freeTree(Tree *n) { - if (!n) return; - freeTree(n->yes); - freeTree(n->no); - free(n); +// кількість листків +int Leaves(Tree *node) { + if (!node) return 0; + if (node->isAnswer) return 1; + + return Leaves(node->yes) + Leaves(node->no); } -void start(Tree *n) { - char in[SIZE]; +// free +void freeTree(Tree *node) { + if (!node) return; - while (n && !n->isAnswer) { - printf("%s\n", n->text); + freeTree(node->yes); + freeTree(node->no); + free(node); +} - if (!fgets(in, SIZE, stdin)) return; +// запуск +void start(Tree *node) { + char input[SIZE]; - int i = 0; - while (in[i] == ' ' || in[i] == '\t' || in[i] == '\r') i++; + while (node && !node->isAnswer) { - if (in[i] == 'a') - n = n->yes; - else - n = n->no; + printf("%s\n", node->text); + + if (fgets(input, SIZE, stdin) == NULL) { + printf("Koniec vstupu\n"); + return; + } + + if (input[0] == 'a') { + node = node->yes; + } + else if (input[0] == 'n') { + node = node->no; + } + else { + printf("Nerozumiem\n"); + return; + } } - if (n) { - printf("*%s\n", n->text); + if (node && node->isAnswer) { + printf("*%s\n", node->text); printf("Koniec\n"); } } @@ -82,7 +110,13 @@ int main() { return 0; } - printf("Pozna %d druhov ovocia a zeleniny.\n", count(root)); + if (!EmptyLine()) { + printf("Chyba nacitania\n"); + freeTree(root); + return 0; + } + + printf("Pozna %d druhov ovocia a zeleniny.\n", Leaves(root)); printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); start(root);