Sams Teach Yourself C in 21 Days

(singke) #1
elements can. As we stated earlier, elements in a list are connected with pointers. Much
of the work of adding and deleting elements consists of manipulating these pointers.
Elements can be added to the beginning, middle, or end of a linked list; this determines
how the pointers must be changed.
Later in today’s lesson you’ll find a simple linked list demonstration, as well as a more
complex working program. Before getting into the nitty-gritty of code, however, it’s a
good idea to examine some of the actions you need to perform with linked lists. For
these sections, we will continue using the personstructure that was introduced earlier.

Preliminaries
Before you start a linked list, you must define the data structure that will be used for the
list, and you also need to declare the head pointer. Because the list starts out empty, the
head pointer should be initialized to NULL. You will also need an additional pointer to
your list structure type for use in adding records. (You might need more than one pointer,
as you’ll soon see.) Here’s how you do it:
struct person {
char name[20];
struct person *next;
};
struct person *new;
struct person *head;
head = NULL;

Adding an Element to the Beginning of a List
If the head pointer is NULL, the list is empty, and the new element will be its only mem-
ber. If the head pointer is not NULL, the list already contains one or more elements. In
either case, however, the procedure for adding a new element to the start of the list is the
same:


  1. Create an instance of your structure, allocating memory space using malloc().

  2. Set the next pointer of the new element to the current value of the head pointer.
    This will be NULLif the list is empty, or the address of the current first element oth-
    erwise.

  3. Make the head pointer point to the new element.
    Here is the code to perform this task:
    new = (person*)malloc(sizeof(struct person));
    new->next = head;
    head = new
    Note that malloc()is typecast so that its return value is the proper type—a pointer to the
    person data structure.


418 Day 15

25 448201x-CH15 8/13/02 11:13 AM Page 418

Free download pdf