Friday, August 29, 2008

Delete All Elements from a Singly Linked List

When we want to remove all the elements from a linked list, the natural inclination is to use a single pointer to traverse the list, freeing elements as we go. A problem arises, however, when this is implemented. Do we advance the pointer or free the element first? If we advance the pointer first, then the freeing is impossible because we overwrote the pointer to the element to be freed. If we free the element first, advancing the pointer is impossible because it involves reading the next pointer in the element that was just freed. The solution is to use two pointers.

Example Code:

void DeleteAllElement( ListElement **head )

{

ListElement *deleteMe = *head;

while( deleteMe )

{

ListElement *next = deleteMe->next;

delete deleteMe;

deleteMe = next;

}

*head = NULL;

}

No comments: