Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 417

15


person—in other words, a pointer to another structure of the same type. This means that
each structure of type personcan not only contain a chunk of data, but also can point to
anotherpersonstructure. Figure 15.7 shows how this lets the structures be linked
together in a list.

FIGURE15.7
Links in a linked list.

data
next pointer

data
next pointer

data
next pointer

NULL

Notice that in Figure 15.7, each personstructure points to the next personstructure. The
lastpersonstructure doesn’t point to anything. The last element in a linked list is identi-
fied by the pointer element being assigned the value of NULL.

The structures that make up a link in a linked list can be referred to as links,
Note nodes,orelementsof a linked list.

You have seen how the last link in a linked list is identified. What about the first link?
This is identified by a special pointer (not a structure) called the head pointer. The head
pointer always points to the first element in the linked list. The first element contains a
pointer to the second element; the second element contains a pointer to the third, and so
on, until you encounter an element whose pointer is NULL. If the entire list is empty (con-
tains no links), the head pointer is set to NULL. Figure 15.8 illustrates the head pointer
before the list is started and after the first list element is added.

FIGURE15.8
A linked list’s head
pointer. data
NULL
Before first addition After first addition

head

NULL

head

Working with Linked Lists ............................................................................

When you’re working with a linked list, you can add, delete, or modify elements or
links. Modifying an element presents no real challenge; however, adding and deleting

Thehead pointeris a pointer to the first element in a linked list. The head
Note pointer is sometimes referred to as the first element pointer or top pointer.

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

Free download pdf