Answer to Quiz 9 Fri 23 Mar 2001

Consider the following linear linked list :
        typedef struct person PERSON;
        struct person
        {
           char   *name;
           int    age;
           PERSON *tail;
        };
  1. The function int CountMinors ( PERSON *l ); returns the number of persons in l of age strictly less than 18. Write a recursive definition of this function below.
            int CountMinors ( PERSON *l )
            {
               if (l == NULL)
                  return 0;
               else if (l -> age < 18)
                  return 1 + CountMinors(l -> tail);
               else
                  return CountMinors(l -> tail);
            }
    
  2. The function void Destroy ( PERSON *l ); frees all memory allocated for l.
    Write an implementation for Destroy below.
            void Destroy ( PERSON *l )
            {
               if (l != NULL)
               {
                  Destroy(l -> tail);
                  free(l -> name);
                  free(l);
               }
            }