/* This program uses code from "Algorithms in C, Third Edition,"
 *               by Robert Sedgewick, Addison-Wesley, 1998.
 */

#include <stdlib.h>
#include <stdio.h>

typedef struct node * link;
struct node  
{
   int item; 
   link next;  
};

/* Creates a new link, that contains the value 
 * specified in the argument, 
 * and that points to NULL. 
 */
link newLink(int value)
{
   link result = malloc(sizeof(struct node));
   result->item = value;
   result->next = NULL;
}

void printList(link my_list)
{
   printf("\n");
   int counter = 0;
   link current_link;
   for (current_link = my_list; current_link != 0; current_link = current_link->next)
   {
      printf("item %d: %d\n", counter, current_link->item);
      counter++;
   }
}


main()
{
   /* our list must be initialized to NULL, until we have the first
    * link created. Then, our list will simply be set equal to that 
    * first link.
    */
   link the_list = NULL;
   link current_link = NULL;

   while(1)
   {
      int number;
      printf("please enter an integer: ");
      int items_read = scanf("%d", &number);
      if (items_read != 1)
      {
         break;
      }
     
      link next_item = newLink(number);

      /* if this is the very first link we are creating, set the list
       * to be equal to this first link, since, in this implementation,
       * we are just representing a list by its first link.
       */
      if (the_list == NULL)
      {
         the_list = next_item;
      }
      else
      {
         current_link->next = next_item;
      }
      current_link = next_item;
   }
   
   /* Go through the list to print the contents.
    * This serves two purposes:
    * 1. Verify that we stored items in the list correctly.
    * 2. Provide an example of how to traverse a list from beginning to end. 
    */
   printList(the_list);
   
   return 0;
}