usaa24/cv7/program.c

110 lines
2.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 256
struct node {
char value[MAX_SIZE];
struct node *left;
struct node *right;
int id;
};
struct node* read_tree(int *id_counter) {
char line[MAX_SIZE];
if (fgets(line, MAX_SIZE, stdin) == NULL || line[0] == '\n') {
return NULL;
}
struct node *new_node = (struct node*)malloc(sizeof(struct node));
if (new_node == NULL) {
return NULL;
}
strcpy(new_node->value, line);
new_node->id = (*id_counter)++;
if (line[0] != '*') {
new_node->left = read_tree(id_counter);
new_node->right = read_tree(id_counter);
}
return new_node;
}
void free_tree(struct node *root) {
if (root == NULL) return;
free_tree(root->left);
free_tree(root->right);
free(root);
}
int count_items(struct node *root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return 1;
return count_items(root->left) + count_items(root->right);
}
void start_system(struct node *current_node) {
if (current_node == NULL) return;
int blank_lines = 0;
int is_first_prompt = 1;
while (current_node != NULL) {
if (current_node->left == NULL && current_node->right == NULL) {
printf("%s", current_node->value);
printf("Koniec\n");
return;
}
if (is_first_prompt) {
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
is_first_prompt = 0;
}
printf("%s", current_node->value);
char response;
int result = scanf(" %c", &response);
if (result == EOF || (response == '\n' && ++blank_lines >= 2)) {
printf("Koniec vstupu\n");
return;
}
if (response == 'a') {
blank_lines = 0;
current_node = current_node->left;
} else if (response == 'n') {
blank_lines = 0;
current_node = current_node->right;
} else {
printf("Nerozumiem\n");
return;
}
}
}
int main() {
int counter = 0;
struct node *root = read_tree(&counter);
printf("Expert z bufetu to vie.\n");
if (root == NULL) {
printf("Chybna databaza\n");
return 0;
}
int item_count = count_items(root);
printf("Pozna %d druhov ovocia a zeleniny.\n", item_count);
start_system(root);
free_tree(root);
return 0;
}