A Journey 2 Eternity

Delete All Elements from a Singly Linked List

Posted on: August 29, 2008

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.

void DeleteAllElement( ListElement **head )
{
	ListElement *deleteMe = *head;
	while( deleteMe ) {
		ListElement *next = deleteMe->next;
		delete deleteMe;

		deleteMe = next;
	}

	*head = NULL;
}
Advertisements

1 Response to "Delete All Elements from a Singly Linked List"

Jazaak Allah. You have not idea how crazy this problem was driving me! This helped a lot! Thankyou very much.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

August 2008
M T W T F S S
« Apr   Sep »
 123
45678910
11121314151617
18192021222324
25262728293031

Blog Stats

  • 27,491 hits
%d bloggers like this: