L-26 MCS 275 Fri 9 Mar 2001

These are the programs we discussed in class:
/* L-26 MCS 275 Fri 9 Mar 2001 creating and printing a list of names */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 80

typedef struct names NAMES;

struct names
{
   char *head;
   NAMES *tail;
};

void print_names ( NAMES *l );
/* prints the elements in a list */

NAMES *rec_create_names ();
/* reads strings given by the user and returns a list, recursively */
NAMES *itr_create_names ();
/* reads strings given by the user and returns a list, iteratively */

int main()
{
   NAMES *l;

   printf("Creating list of strings...\n");

   l = itr_create_names();

   printf("Printing the list : ");
   print_names(l);
   printf("\n");

   return 0;
}

void print_names ( NAMES *l )
{
   if (l != NULL) 
   {
      printf(" %s", l->head);
      print_names(l->tail);
   }
}

NAMES *rec_create_names ()
{
   NAMES *l;
   char s[MAX];

   printf("  Give string (0 to stop) : ");
   scanf("%s", s);

   if (s[0] == '0')
      l = NULL;
   else
   {
      l = (NAMES*)calloc(1,sizeof(NAMES));
      l->head = s;
      l->tail = rec_create_names();
   }

   return l;
}

NAMES *itr_create_names ()
{
   NAMES *l,*previous,*current;
   int stop = 0;
   int first = 1;
   char s[MAX];

   while (stop == 0)
   {
      printf("  Give a string (0 to stop) : ");
      scanf("%s", s);

      if (s[0] == '0')
      {
         stop = 1;
         if (first == 1)
            l = NULL;
         else
            current = NULL;
      }
      else
      {
         current = (NAMES*)calloc(1,sizeof(NAMES));
         current->head = (char*)calloc(strlen(s),sizeof(char));
         strcpy(current->head,s);
         if (first == 1)
         {
            l = current;
            first = 0;
         }
         else
            previous->tail = current;
         previous = current;
      }
   }

   return l;
}