home *** CD-ROM | disk | FTP | other *** search
- #include <stdio.h>
-
- typedef struct { int key; } LEAF;
-
- #include "tree.h"
-
- /* -------------------------------------------------------------------------- */
-
- prnt(stream, p)
- FILE *stream;
- LEAF *p;
- {
- fprintf( stream, p ? "%2d" : " ", p->key );
- }
-
- /* -------------------------------------------------------------------------- */
-
- icmp(n1,n2) /* comparison routine for insert() to use */
- LEAF *n1, *n2;
- {
- return(n1->key - n2->key);
- }
-
- dcmp(key, n2) /* comparison routine for delete() and find() */
- int key;
- LEAF *n2;
- {
- return(key - n2->key);
- }
-
- /* -------------------------------------------------------------------------- */
-
- docmd( cmd, n)
- {
- static TREE *root = NULL;
- LEAF *p, *p2;
-
- switch(cmd)
- {
- case 'd':
- case 'D':
- if( !delete(&root, (LEAF *) n, dcmp) )
- fprintf(stderr, "Node is NOT in tree\n");
- break;
-
- case 'f':
- case 'F':
- if(p = find(root, (LEAF *) n, dcmp) )
- fprintf(stderr, "Node %d found\n", p->key);
- else
- fprintf(stderr, "Node NOT found\n" );
- break;
-
- case 'i':
- case 'I':
- if( !(p = talloc(sizeof(LEAF))) )
- fprintf(stderr, "Out of memory\n");
- else
- {
- p->key = n;
- if(p2 = insert(&root, p, icmp) )
- {
- fprintf(stderr, "%d is already in the tree\n",p2->key);
- tfree(p);
- }
- }
- break;
-
- case 'a':
- case 'A':
- freeall(&root);
- break;
-
- case 'q':
- case 'Q':
- exit(0);
- }
-
- tprint( root, prnt, stdout );
- printf("\n");
- }
-
- /* -------------------------------------------------------------------------- */
-
- main(argc, argv)
- int argc;
- char **argv;
- {
- /* Assemble a tree, first get commands from the command line
- until these are exhausted, then get commands from the
- keyboard.
- */
-
- char buf[128];
-
- for(++argv; --argc > 0; ++argv)
- docmd( **argv, atoi(*argv + 1) );
-
- printf("commands are: iN -insert node N into tree\n");
- printf(" dN -delete node N\n");
- printf(" fN -find node N\n");
- printf(" a -delete entire tree\n");
- printf(" q -quit (exit)\n");
-
- for(; gets(buf); printf("i/d/f/a/q: ") )
- docmd(*buf, atoi(buf+1) );
- }