diff options
Diffstat (limited to 'rb_tree_main.c')
-rw-r--r-- | rb_tree_main.c | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/rb_tree_main.c b/rb_tree_main.c new file mode 100644 index 0000000..e90910d --- /dev/null +++ b/rb_tree_main.c @@ -0,0 +1,94 @@ +#include "rb_tree.h" +#include <stdio.h> +#include <stdlib.h> + +#define PRINT_MENU \ + printf("\n1 - add numbers to tree\n"); \ + printf("2 - remove node if it exists\n"); \ + printf("3 - print tree\n"); \ + printf("4 - clear tree\n"); \ + printf("5 - quit\n"); + +#define CLEAR_BUFFER \ + while ( (res = getchar()) != '\n' && res != EOF ) { } + +int main() +{ + enum { true = 1 }; + enum state { add = 1, remove, print, clear, quit }; + enum state answer; + rb_tree *new_tree = NULL; + int res, num; + char ch; + while(true) { + PRINT_MENU + if((res = getchar())== EOF) + break; + ch = (char)res; + res = strtol(&ch, NULL, 10); + if(!res) { + CLEAR_BUFFER + printf("\e[1;1H\e[2J"); /* clear screen */ + continue; + } + answer = (enum state) res; + CLEAR_BUFFER + printf("\e[1;1H\e[2J"); + switch(answer) { + case add: + if(!new_tree) { + new_tree = malloc(sizeof(rb_tree)); + rb_tree_init(new_tree); + } + printf("enter some numbers (ctrl-d - quit)\n"); + while((res = scanf("%d", &num)) != EOF) { + if(!res) { + fprintf(stderr, "invalid input\n"); + return 1; + } + node *new_node = rb_tree_create_node(new_tree, num); + if (new_node) + rb_tree_insert_node(new_tree, new_node); + } + clearerr(stdin); + break; + case remove: + if(!new_tree) { + printf("tree wasn't created\n"); + break; + } + printf("enter a number to delete\n"); + res = scanf("%d", &num); + if(!res) { + fprintf(stderr, "invalid input\n"); + return 1; + } + node *del_node = rb_tree_search(new_tree, new_tree->root, num); + if(del_node != new_tree->nil) { + rb_tree_delete_node(new_tree, del_node); + printf("node with this number has been removed!\n"); + } + else + printf("the number wasn't finded\n"); + CLEAR_BUFFER + break; + case print: + if(new_tree) + rb_tree_print(new_tree, new_tree->root); + break; + case clear: + if(new_tree) { + rb_tree_clear(new_tree, new_tree->root); + free(new_tree); + new_tree = NULL; + printf("tree has been cleared\n"); + } + break; + case quit: + if(new_tree) + free(new_tree); + return 0; + } + } + return 0; +} |