01.01.2013 Views

AT&T UNIX™PC Unix System V Users Manual - tenox

AT&T UNIX™PC Unix System V Users Manual - tenox

AT&T UNIX™PC Unix System V Users Manual - tenox

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

TSEARCH ( 3C ) TSEARCH ( 3C )<br />

data type typedef enum { preorder, postorder, endorder, leaf }<br />

VISIT; (defined in the header file), depending on<br />

whether this is the first, second, or third time that the node has<br />

been visited (during a depth-first, left-to-right traversal of the<br />

tree), or whether the node is a leaf. The third argument is the �<br />

level of the node in the tree, with the root being level zero. ·�<br />

The pointers to the key and the root of the tree should be of type<br />

pointer-to-element, and cast to type pointer-to-character. Similarly,<br />

although declared as type pointer-to-character, the value<br />

returned should be cast into type pointer-to-element.<br />

EXAMPLE<br />

The following code reads in strings and stores structures containing<br />

a pointer to each string and a count of its length. It then<br />

walks the tree, printing out the stored strings and their lengths in<br />

alphabetical order.<br />

#include <br />

#include <br />

struct node { /*pointers to these are stored in the tree*/<br />

char *string;<br />

int length;<br />

};<br />

char string_space[lOOOO];<br />

struct node nodes[500J ;<br />

struct node *root = NULL;<br />

root*/<br />

main( )<br />

{<br />

}<br />

I*<br />

char *strptr = string_space;<br />

struct node *nodeptr = nodes;<br />

void print_node( ), twalk( );<br />

int i = 0; node_compare( );<br />

/*space to store strings*/<br />

/*nodes to store*/<br />

/*this points to the<br />

while (gets(strptr) != NULL && i++ < 500) {<br />

/*set node*/<br />

nodeptr- >string = strptr;<br />

nodeptr- > length = strlen(strptr);<br />

j*put node into the tree*/<br />

(void) tsearch(( char *)nodeptr, (char **)<br />

&root,<br />

node_compare );<br />

/*adjust pointers so we don't overwrite<br />

tree*/ �<br />

strptr += nodeptr->length + 1;<br />

l<br />

nodeptr++;<br />

}<br />

twalk((char *)root, print_node);<br />

This routine compares two nodes, based on an<br />

- 2 -

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!