Friday, August 29, 2008

Tracking the Head Element of a Singly Linked List

The head element of a singly-linked list must always be tracked; otherwise, the list will be lost in memory. This means that the pointer or reference to the head of the list must be updated when a new element is inserted ahead of the first element or when the existing first element is removed from the list. Tracking the head element becomes a problem when you alter the list inside a function or method, because the caller must be made aware of the new head element.

Example Code:

bool InsertInFront( ListElement **head, int data )

{

ListElement *newElem = new ListElement;

if( !newElem ) return false;

newElen->data = data;

*head = newElem;

return true;

}

No comments: