From ea6d529fad064f53da29a6fc8d6fc3f691c92b33 Mon Sep 17 00:00:00 2001 From: Kozar Date: Sun, 10 Nov 2024 15:36:06 +0000 Subject: [PATCH] Initializacia --- cv7/program.c | 67 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 25 deletions(-) diff --git a/cv7/program.c b/cv7/program.c index c363c36..970b30e 100644 --- a/cv7/program.c +++ b/cv7/program.c @@ -1,23 +1,26 @@ -#include -#include -#include -#include +#include +#include +#include +#include #define SIZE 100 -struct tree{ +struct tree { char value[SIZE]; struct tree* left; struct tree* right; }; -struct tree* read_tree(){ +struct tree* read_tree() { char buffer[SIZE]; - memset(buffer,0,SIZE); - char* r = fgets(buffer,SIZE,stdin); - assert(r); - struct tree* node = calloc(1,sizeof(struct tree)); - memcpy(node->value,buffer,SIZE); + memset(buffer, 0, SIZE); + char* r = fgets(buffer, SIZE, stdin); + if (!r || buffer[0] == '\n') { + return NULL; + } + buffer[strcspn(buffer, "\n")] = 0; + struct tree* node = calloc(1, sizeof(struct tree)); + strncpy(node->value, buffer, SIZE - 1); return node; } @@ -33,33 +36,47 @@ struct tree* load_tree() { return node; } -void print_tree(struct tree* tree, int offset){ - for (int i = 0; i < offset; i++){ - printf(" "); +void print_tree(struct tree* tree, int offset) { + if (!tree) { + return; } - printf("%s", tree->value); - if (tree->left){ + + if (tree->value[0] == '*') { + printf("Expert z bufetu to vie.\n%s\nKoniec\n", tree->value + 1); + return; + } + + printf("%s\n", tree->value); + + char response; + if (scanf(" %c", &response) != 1 || (response != 'a' && response != 'n')) { + printf("Nespravny vstup. Koniec.\n"); + return; + } + + if (response == 'a') { print_tree(tree->left, offset + 3); + } else { print_tree(tree->right, offset + 3); } } -void destroy_tree(struct tree* tree){ - if(tree->left != NULL){ +void destroy_tree(struct tree* tree) { + if (tree->left != NULL) { destroy_tree(tree->left); } - if(tree->right != NULL){ + if (tree->right != NULL) { destroy_tree(tree->right); } free(tree); } -void count_items(struct tree* tree, int* count){ - if(tree->left == NULL && tree->right == NULL){ +void count_items(struct tree* tree, int* count) { + if (tree->left == NULL && tree->right == NULL) { (*count)++; - }else{ - count_items(tree->left, count); - count_items(tree->right, count); + } else { + count_items(tree->left, count); + count_items(tree->right, count); } } @@ -75,7 +92,7 @@ int main() { printf("Pozna %d druhov ovocia a zeleniny.\n", count); printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); - print_tree(root); + print_tree(root, 0); destroy_tree(root); return 0;