L-25 MCS 275 Wed 7 Mar 2001

In lecture, we wrote operations on polynomials, but here are the equivalent functions I had prepared for lists of positive integers:
/* L-25 MCS 275 Wed 7 Mar 2001 creating and printing a linear list */

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

typedef struct list LIST;

struct list
{
   int  head;
   LIST *tail;
};

void rec_print_list ( LIST l );
/* prints the elements in a list, recursive version */
void itr_print_list ( LIST l );
/* prints the elements in a list, iterative version */

LIST *rec_create_list ();
/* returns list of positive numbers given by the user, recursive version */
LIST *itr_create_list ();
/* returns list of positive numbers given by the user, iterative version */

int main()
{
   LIST *l;

   printf("Creating list of positive numbers...\n");

   l = itr_create_list();
   /* l = rec_create_list(); */

   if (l == NULL)
      printf("Empty list, nothing to print.\n");
   else
   {
      printf("Printing the list (recursively) : ");
      rec_print_list(*l);
      printf("\n");
      printf("Printing the list (iteratively) : ");
      itr_print_list(*l);
      printf("\n");
   }

   return 0;
}

void rec_print_list ( LIST l )
{
   printf(" %d", l.head);
   if (l.tail != NULL) 
      rec_print_list(*l.tail);
}

void itr_print_list ( LIST l )
{

   LIST *p;

   for (p = &l; p != NULL; p = p->tail)
      printf(" %d", p->head);
}

LIST *rec_create_list ()
{
   LIST *l;
   int n;

   printf("  Give positive number (0 to stop) : ");
   scanf("%d", &n);

   if (n == 0)
      l = NULL;
   else
   {
      l = (LIST*)calloc(1,sizeof(LIST));
      l->head = n;
      l->tail = rec_create_list();
   }

   return l;
}

LIST *itr_create_list ()
{
   LIST *l,*previous,*current;
   int n = 1;
   int first = 1;

   while (n > 0)
   {
      printf("  Give positive number (0 to stop) : ");
      scanf("%d", &n);

      if (n == 0)
      {
         if (first == 1)
            l = NULL;
         else
            current = NULL;
      }
      else
      {
         current = (LIST*)calloc(1,sizeof(LIST));
         current->head = n;
         if (first == 1)
         {
            l = current;
            first = 0;
         }
         else
            previous->tail = current;
         previous = current;
      }
   }

   return l;
}