Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 423

15


current2= current1->next;
}
free(current1->next);
current1->next = null;
if (head == current1)
head = null;
Finally, the following code deletes an element from within the list:
person *current1, *current2;
/* Code goes here to have current1 point to the */
/* element just before the one to be deleted. */
current2 = current1->next;
free(current1->next);
current1->next = current2->next;
After any of these procedures, the deleted element still exists in memory, but it is
removed from the list because there is no pointer in the list pointing to it. In a real-world
program, you would want to reclaim the memory occupied by the deleted element. This
is accomplished with the free()function. You’ll learn about this function in detail on
Day 20.

A Simple Linked List Demonstration ..........................................................

Listing 15.12 demonstrates the basics of using a linked list. This program is clearly for
demonstration purposes only, because it doesn’t accept user input and doesn’t do any-
thing useful other than show the code required for the most basic linked list tasks. The
program does the following:


  1. It defines a structure and the required pointers for the list.

  2. It adds the first element to the list.

  3. It adds an element to the end of the list.

  4. It adds an element to the middle of the list.

  5. It displays the list contents on-screen.


LISTING15.12 linkdemo.c. The basics of a linked list
1: /* Demonstrates the fundamentals of using */
2: /* a linked list. */
3:
4: #include <stdlib.h>
5: #include <stdio.h>
6: #include <string.h>
7:
8: /* The list data structure. */
9: struct data {

INPUT

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

Free download pdf