Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 431

15


222490 3 c 222450
222450 4 q 222480
222480 5 z 0

Note Your output will probably show different address values.


This program demonstrates adding a link to a linked list. It isn’t the easiest list-
ing to understand; however, if you walk through it, you’ll see that it’s a combina-
tion of the three methods of adding links that were discussed earlier. This listing can be
used to add links to the beginning, middle, or end of a linked list. Additionally, this list-
ing takes into consideration the special cases of adding the first link (the one that gets
added to the beginning) and the second link (the one that gets added to the middle).

The easiest way to fully understand this listing is to step through it line-by-
line in your compiler’s debugger and to read the following analysis. By see-
ing the logic executed, you will better understand the listing.

Tip


Several items at the beginning of Listing 15.13 should be familiar or easy to understand.
Lines 9 through 11 check to see whether the value of NULLis already defined. If it isn’t,
line 10 defines it to be 0. Lines 14 through 22 define the structure for the linked list and
also declare the type definitions to make working with the structure and pointers easier.
Themain()function should be easy to follow. A head pointer called firstis declared in
line 31. Notice that this is initialized to NULL. Remember that you should never let a
pointer go uninitialized. Lines 36 through 49 contain a whileloop that is used to get five
characters from the user. Within this outer whileloop, which repeats five times, a
do...whileis used to ensure that each character entered is a letter. The isalpha()func-
tion could have been used just as easily.
After a piece of data is obtained,add_to_list()is called. The pointer to the beginning
of the list and the data being added to the list are passed to the function.
Themain()function ends by calling show_list()to display the list’s data and then
free_memory_list()to release all the memory that was allocated to hold the links in the
list. Both these functions operate in a similar manner. Each starts at the beginning of the
linked list using the head pointer first. A whileloop is used to go from one link to the
next using the next_ptrvalue. When next_ptris equal to NULL, the end of the linked
list has been reached, and the functions return.

ANALYSIS

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

Free download pdf