I am trying to write a delete algorithm for an ordered linked list. Search and traverse I think I have down but delete is giving me fits. It crashes every time. Any help is greatly appreciated!
I have a private pointer to a ListNode strcuture called head in my TestLL class. The ListNode structure contains int Key, double dataValue, and ListNode *next. The function returns true if the node to delete was found and deleted or false if it was not found.
Code:
bool TestLL::Delete(int Key)
{
ListNode *back = NULL, *temp = head;
//Search for the node to delete
while((temp != NULL) && (key != temp -> key))
{
//advance the pointers
back = temp;
temp = temp->next;
}
//Check for node to delete not being found
if( temp == NULL)
{
return false;
}
//Check for deleting the head of the list
else if( back == NULL) //I'm very unsure of my else if and else
{
return false;
}
else// Remove node other than at the head
{
delete temp;
}
//deallocate memory used by the removed node
free(temp);
return true;
}