Listing 4

/*
 * xrt.c - cross-reference table
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "ln_seq.h"
#include "xrt.h"

struct treenode
   {
   char *word;
   ln_seq lines;
   treenode *left, *right;
   };

static treenode *addtree
      (treenode *t, char *w, unsigned n)
   {
   int cond;

   if (t == 0)
      {
      t = new treenode;
      t->word
         = strcpy((char *)malloc(strlen(w) + 1),
w);
      t->lines.add(n);
      t->left = t->right = 0;
      }

   else if ((cond = strcmp(w, t->word)) == 0)
      t->lines.add(n);
   else if (cond < 0)
      t->left = addtree(t->left, w, n);
   else
      t->right = addtree(t->right, w, n);
   return t;
   }

static void printtree(treenode *t)
   {
   if (t != 0)
      {
      printtree(t->left);
      printf("%12s: ", t->word);
      t->lines.print();
      printf("\n");
      printtree(t->right);
      }
   }

static treenode *root = 0;

void xrt_add(char *w, unsigned n)
   {
   root = addtree(root, w, n);
   }

void xrt_print(void)
   {
   printtree(root);
   }