我正在尝试为有序链表编写删除算法。搜索和遍历我认为我已经失败但删除让我很适应。每次都会崩溃。有人可以帮我解决这个问题吗?
我有一个指向我的类中ListNode
调用的结构的私有指针。该结构包含、和。如果找到并删除了要删除的节点,或者没有找到,该函数返回。head
TestLL
ListNode
int Key
double dataValue
ListNode *next
true
false
我的代码:
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
{
delete temp;
}
else // Remove node other than at the head
{
delete temp;
}
//deallocate memory used by the removed node
free(temp);
return true;
}