diff --git a/cv7/program.c b/cv7/program.c index cbda220..4ba61f1 100644 --- a/cv7/program.c +++ b/cv7/program.c @@ -1,23 +1,25 @@ -#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; } @@ -29,55 +31,79 @@ struct tree* load_tree() { if (node->value[0] != '*') { node->left = load_tree(); node->right = load_tree(); + } else if (node->left != NULL || node->right != NULL) { + printf("Expert z bufetu to vie.\n"); + free(node); + return NULL; } return node; } -void print_tree(struct tree* tree, int offset){ - for (int i = 0; i < offset; i++){ - printf(" "); +void run_tree(struct tree* tree) { + if (!tree) { + return; } - printf("%s", tree->value); - if (tree->left){ - print_tree(tree->left, offset + 3); - print_tree(tree->right, offset + 3); + + if (tree->value[0] == '*') { + printf("*%s\nKoniec\n", tree->value + 1); + return; + } + + printf("%s\n", tree->value); + + char response; + if (scanf(" %c", &response) != 1) { + printf("Koniec vstupu\n"); + return; + } else if (response != 'a' && response != 'n') { + printf("Nerozumiem\n"); + return; + } + + if (response == 'a') { + run_tree(tree->left); + } else { + run_tree(tree->right); } } -void destroy_tree(struct tree* tree){ - if(tree->left != NULL){ +void destroy_tree(struct tree* tree) { + if (tree) { destroy_tree(tree->left); - } - if(tree->right != NULL){ destroy_tree(tree->right); + free(tree); } - free(tree); } -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); +void count_items(struct tree* tree, int* count) { + if (tree) { + if (tree->left == NULL && tree->right == NULL) { + (*count)++; + } else { + count_items(tree->left, count); + count_items(tree->right, count); + } } } int main() { - printf("Nacitanie baze pravidiel:\n"); struct tree* root = load_tree(); + + printf("Expert z bufetu to vie.\n"); if (!root) { - printf("Chyba: Nepodarilo sa nacitat bazu pravidiel.\n"); - return 1; + printf("Chybna databaza\n"); + return 0; } + int count = 0; count_items(root, &count); printf("Pozna %d druhov ovocia a zeleniny.\n", count); - printf("Strom pre ladenie:\n"); - print_tree(root, 0); + printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); + + run_tree(root); destroy_tree(root); return 0; -} +} \ No newline at end of file