Page 114 - Programming Microcontrollers in C
P. 114

Structures     99

                          this program. This function receives a pointer to a Tnode and a pointer
                          to a character string as arguments. It returns a pointer to a Tnode. If
                          the Tnode pointer argument is a NULL on entry to the function, the
                          first if loop is executed. Within that loop, talloc() returns a pointer
                          to a new Tnode. The function strsave() copies the string into a
                          safe place and returns a pointer to this location. This pointer is put into
                          the word pointer location in the new Tnode. A value of 1 is put into
                          the count location, and the pointers to the left and right child Tnodes
                          are set to NULL. At this time, the word has been put into the Tnode ,
                          and the pointer to this Tnode is returned to the calling program.

                   /* addtree: add a node with w, at or below p */

                   Tnode *addtree(Tnode *p, char *w)
                   {
                       int cond;

                       if(p == NULL) /* new word has arrived */
                       {
                          p=talloc(); /* make a new node */
                          p->word=strsave(w);
                          p->count=1;
                          p->left=p->right=NULL;
                       }
                       else if((cond = strcmp(w,p->word)) == 0 )
                          p->count++; /* repeated word */
                       else if(cond <0) /* less than into left subtree*/
                       p->left = addtree(p->left,w);
                       else /* greater than into right subtree */
                          p->right = addtree(p->right,w);
                       return p;
                   }
                              Suppose now that at a later time addtree() is called and this
                          time p is no longer a NULL. In this case, a string compare test will be
                          executed to determine if the word that has been passed is equal to that
                          in the Tnode pointed to by p. If it is equal, it is a repeated word for
                          that node, so the word count is incremented and control is returned to
                          the calling program. If it is not equal (say, it is lexically less than the
   109   110   111   112   113   114   115   116   117   118   119