twitter
    Find out what I'm doing, Follow Me :)

A Linked List

We finally come to the grandaddy of all programming techniques as far as being intimidating. Load the program dynlink.c for an example of a dynamically allocated linked list. It sounds terrible, but after a little time spent with it, you will see that it is simply another programming technique made up of simple components that can be a powerful tool.

#include "stdio.h" /* this is needed only to define the NULL */
#define RECORDS 6
main( )
{
struct animal {
char name[25]; /* The animals name */
char breed[25]; /* The type of animal */
int age; /* The animals age */
struct animal *next; /* a pointer to another record of this type */
} *point, *start, *prior; /* this defines 3 pointers, no variables */
int index;
/* the first record is always a special case */
start = (struct animal *)malloc(sizeof(struct animal));
strcpy(start ->name,"general");
strcpy(start ->breed,"Mixed Breed");
start->next = NULL;
prior = start;
/* a loop can be used to fill in the rest once it is started */
for (index = 0;index < RECORDS;index++) {
point = (struct animal *)malloc(sizeof(struct animal));
strcpy(point->name,"Frank");
strcpy(point->breed,"Laborador Retriever");
point->age = 3;
point->next = point /* point last "next" to this record */
point->next = NULL; /* point this "next" to NULL */
prior = point; /* this is now the prior record */
}
/* now print out the data described above */
point = start;
do {
prior = point->next;
printf("%s is a %s,and is %d years old.\n", point->name,
point->breed, point->age);
point = point->next;
} while (prior != NULL);
/* good programming practice dictates that we free up the */
/* dynamically allocated space before we quit */
point = start; /* first block of group */
do {
prior = point->next; /* next block of data */
free(point); /* free present block */
point = prior; /* point to next */
} while (prior != NULL); /* quit when next is NULL */
}


In order to set your mind at ease, consider the linked list you used when you were a child. Your sister gave you your birthday present, and when you opened it, you found a note that said, "Look in the hall closet." You went to the hall closet, and found another note that said, "Look behind the TV set." Behind the TV you found another note that said, "Look under the coffee pot." You continued this search, and finally you found your pair of socks under the dogs feeding dish. What you actually did was to execute a linked list, the starting point being the wrapped present and the ending point being under the dogs feeding dish. The list ended at the dogs feeding dish since there were no more notes.

In the program dynlink.c, we will be doing the same thing as your sister forced you to do. Wewill however, do it muchfaster and wewill leave a little pile of data at each of the intermediate points along the way. We will also have the capability to return to the beginning and retraverse the entire list again and again if we so desire.