#include #include #include "splay.h" #include "fields.h" prepostorder(int pre, Splay *bn, int depth) { int i; if (bn == NULL) return; if (pre == -1) { for (i = 0; i < depth; i++) printf(" "); printf("%s %.2lf\n", jval_s(bn->key), jval_d(bn->val)); } prepostorder(pre, bn->left, depth+2); if (pre == 0) { for (i = 0; i < depth; i++) printf(" "); printf("%s %.2lf\n", jval_s(bn->key), jval_d(bn->val)); } prepostorder(pre, bn->right, depth+2); if (pre == 1) { for (i = 0; i < depth; i++) printf(" "); printf("%s %.2lf\n", jval_s(bn->key), jval_d(bn->val)); } } traverse(Splay *b) { Splay *bn; splay_traverse(bn, b) { printf("%-30s %10.2lf\n", jval_s(bn->key), jval_d(bn->val)); } } main() { Splay *b; Splay *bn; IS is; double dval; is = new_inputstruct(NULL); b = new_splay(); while (1) { printf("SPLAY_TEST> "); fflush(stdout); if (get_line(is) < 0) exit(0); if (is->NF > 0) { if (strcmp(is->fields[0], "INSERT") == 0) { if (is->NF != 3) { printf("INSERT name value\n"); } else if (sscanf(is->fields[2], "%lf\n", &dval) != 1) { printf("INSERT name value -- value must be a number\n"); } else { (void) splay_insert_str(b, strdup(is->fields[1]), new_jval_d(dval)); } } else if (strcmp(is->fields[0], "DELETE") == 0) { if (is->NF != 2) { printf("DELETE name\n"); } else { bn = splay_find_str(b, is->fields[1]); if (bn == NULL) { printf("No %s in the tree\n", is->fields[1]); } else { splay_delete_node(bn); } } } else if (strcmp(is->fields[0], "FIND") == 0) { if (is->NF != 2) { printf("FIND name\n"); } else { bn = splay_find_str(b, is->fields[1]); if (bn == NULL) { printf("No %s in the tree\n", is->fields[1]); } else { printf("%-30s %10.2lf\n", jval_s(bn->key), jval_d(bn->val)); } } } else if (strcmp(is->fields[0], "INORDER") == 0) { if (is->NF != 1) { printf("INORDER takes no arguments\n"); } else { prepostorder(0, splay_root(b), 0); } } else if (strcmp(is->fields[0], "PREORDER") == 0) { if (is->NF != 1) { printf("PREORDER takes no arguments\n"); } else { prepostorder(-1, splay_root(b), 0); } } else if (strcmp(is->fields[0], "MAX") == 0) { if (is->NF != 1) { printf("MAX takes no arguments\n"); } else { bn = splay_last(b); if (bn == NULL) { printf("No maximum element\n"); } else { printf("%s %.2lf\n", jval_s(bn->key), jval_d(bn->val)); } } } else if (strcmp(is->fields[0], "MIN") == 0) { if (is->NF != 1) { printf("MIN takes no arguments\n"); } else { bn = splay_first(b); if (bn == NULL) { printf("No minimum element\n"); } else { printf("%s %.2lf\n", jval_s(bn->key), jval_d(bn->val)); } } } else if (strcmp(is->fields[0], "POSTORDER") == 0) { if (is->NF != 1) { printf("POSTORDER takes no arguments\n"); } else { prepostorder(1, splay_root(b), 0); } } else if (strcmp(is->fields[0], "TRAVERSE") == 0) { if (is->NF != 1) { printf("TRAVERSE takes no arguments\n"); } else { traverse(b); } } else if (strcmp(is->fields[0], "QUIT") == 0) { exit(0); } else { printf("Valid commands are INSERT DELETE FIND INORDER PREORDER POSTORDER TRAVERSE MAX MIN QUIT\n"); } } } }