home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The C Users' Group Library 1994 August
/
wc-cdrom-cusersgrouplibrary-1994-08.iso
/
listings
/
v_09_10
/
9n10043a
< prev
next >
Wrap
Text File
|
1991-07-09
|
2KB
|
91 lines
#include <stdio.h>
#define DEBUG
#include "heaptst1.h"
#define MAX_LINE 256
struct node {
struct node * left;
struct node * right;
char * data;
};
struct node * insert(struct node *, struct node *);
struct node * build_node(char *);
char * getnext(void);
void walk_tree(struct node *);
void free_tree(struct node *);
void main()
{
char * word;
struct node *root, *new;
root = NULL;
free(root); /* error */
do {
word = getnext();
new = build_node(word);
root = insert(new,root);
} while (word != NULL);
walk_tree(root);
free_tree(root);
exit(0);
}
struct node * insert(struct node * new, struct node * tree)
{
if (tree==NULL) return new;
if (new == NULL) return tree;
if (strcmp(new->data,tree->data) < 0)
tree->left = insert(new,tree->left);
else
tree->right = insert(new,tree->right);
return tree;
}
struct node * build_node(char * word)
{
struct node * new;
if (word == NULL) return NULL;
new = (struct node *) malloc( sizeof(struct node));
new->right = new->left = NULL;
new->data = word;
return new;
}
char * getnext(void)
{
char * new;
char buffer[MAX_LINE];
if ( gets(buffer) == NULL) return NULL;
new = (char *) malloc( strlen(buffer)+1);
strcpy(new,buffer);
return new;
}
void walk_tree(struct node * tree)
{
if (tree == NULL) return;
if (tree->left != NULL) walk_tree(tree->left);
if (tree->data != NULL) printf("%s\n",tree->data);
if (tree->right != NULL) walk_tree(tree->right);
}
void free_tree(struct node * tree)
{
if (tree == NULL) return;
if (tree->left != NULL)
free_tree(tree->left);
if (tree->right != NULL)
free_tree(tree->right);
if (tree->data != NULL)
free(tree->data);
free(tree);
free(tree); /* error */
}