Deleting an Element from the List
Deleting an element from a linked list is a simple matter of manipulating pointers. The
exact process depends on where in the list the element is located:
- To delete the first element, set the head pointer to point to the second element in
the list. - To delete the last element, set the next pointer of the next-to-last element to NULL.
- To delete any other element, set the next pointer of the element before the one
being deleted to point to the element after the one being deleted.
In addition, the memory of the element that is removed from the list should be freed so
the program does not claim more memory than it needs (this is called a memory leak).
Freeing memory is done with the free()function, which is explained in detail on Day
- Here’s the code to delete the first element in a linked list:
free(head);
head = head->next;
This code deletes the last element in the list:
person current1, current2;
current1 = head;
current2= current1->next;
while (current2->next != NULL)
{
current1 = current2;
422 Day 15
FIGURE15.12
Adding a new element
to the middle of a
linked list. data
next pointer
data
next pointer
new data
NULL
data
NULL
head
Before addition
data
next pointer
data
next pointer
new data
next pointer
data
NULL
head
After addition
25 448201x-CH15 8/13/02 11:13 AM Page 422