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

/* declare a self-referential structure */
typedef  struct elephant {
     char             name[ 10 ];
     struct elephant  *next;
} ELEPHANT;

void      print_elephants( const ELEPHANT *ptr );
ELEPHANT  *get_elephants( void ), *start;

main()
{
     start = get_elephants();
     print_elephants( start );

     return EXIT_SUCCESS;
}

/*   get_elephants allocates run-time storage for nodes. It builds
     the linked list and stores user-supplied names in the name
     fields of the nodes. It returns a pointer to the first such
     node.                                                         */

ELEPHANT *get_elephants( void )
{
     ELEPHANT  *current, *first;
     int response;

     /* allocate first node */
     current = first = malloc( sizeof ( ELEPHANT ) );

     /* store name of first elephant */
     printf( "\n\n\tNAME:\t" );
     scanf( "%s", current -> name );

     /* prompt user about another elephant */
     printf( "\n\n\n\tAdd another? (1 == yes, 0 == no)\t" );
     scanf( "%d", &response );

     /* Add elephants to list until user signals halt. */
     while ( response ) {
          /* try to allocate another elephant node */
          if ( ( current -> next =
               malloc( sizeof ( ELEPHANT ) ) ) ==
               NULL ) {

               printf( "Out of memory\nCan't add more elephants\n" );
               return first;

          }
          current = current -> next;

          /* store name of next elephant */
          printf( "\n\n\tNAME:\t" );
          scanf( "%s", current -> name );

          /* prompt user about another elephant */
          printf( "\n\n\n\tAdd another? (1 == yes, 0 == no)\t" );
          scanf( "%d", &response );
     }

     /* set link field in last node to NULL */
     current -> next = NULL;

     return first;
}

/*   print_elephants steps through the linked list pointed to by ptr
     and prints the name field in each node as well as the position
     of the node in the list                                       */

void  print_elephants( const ELEPHANT *ptr )
{
     int count = 1;

     printf( "\n\n\n" );
     while ( ptr !=  NULL ) {
          printf( "\nElephant number %d is %s.",
               count++, ptr -> name );
          ptr = ptr -> next;
     }
}
