Ok I\'m having a problem with this function that should delete an item from a li
ID: 3624317 • Letter: O
Question
Ok I'm having a problem with this function that should delete an item from a linked list, but it causes the program to crash. This linked list implementation uses nodes that have a data part and a pointer named next that points to the next node in the list. The list has been properly constructed so I believe the problem with using this function is an error in the definition. I'm using C++Here's the code segment:
bool Library::erase(const KeyType &key)
{
NodePointer ptr = first;
NodePointer prevPtr = NULL;
// Loops through the entire list until a match is found (or not found)
while (ptr != NULL)
{
if (ptr->data.key == key) // A match has been found!
{
if (prevPtr = NULL) // If previous pointer is the first, fix
{
first = ptr->next;
}
else // Or, fixes the previous node's pointer
{ // if it's anywhere else in the list
prevPtr->next = ptr->next; //This is where the problem is I think
}
delete ptr;
return true;
}
prevPtr = ptr;
ptr = ptr->next;
}
I deleted the part where I think the problem is and the function worked fine.
Explanation / Answer
prevPtr->next = ptr->next; actually removes the node from the list, and is correct. It fixes the pointers so that the deleted node is never linked in the list. If you delete that line, the code will run, but it won't erase the node. In fact, your erase method looks good. Check the list construction.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.