Reputation: 345
I have a sorted linked list and im trying to create a function to delete whatever the user passes to nameToSearch. but i keep geting an error. Below is what i have so far
void deleteProduct(NodePtr head, char* nameToSearch)
{
NodePtr nodeUnderEdit = findNodeByName(head, nameToSearch);
if (nodeUnderEdit == NULL)
{
cout<<"\n ERROR: Product not found \n";
}
else
{
delete nodeUnderEdit;
nodeUnderEdit = nodeUnderEdit->next;
}
}
Upvotes: 0
Views: 911
Reputation: 1016
To remove an item in a singly linked list you must change the pointer from the Previous record to point to the Next record. It is not sufficient for your "findNodeByName" to just find the node with the matching name. It must find the node Previous to it in the sort order, then set the Next pointer of that record of the Next point of the record to be deleted. Only after you have updated the Next pointer of the Previous record can you delete the record you searched for.
Upvotes: 1
Reputation: 490138
This is always a problem with a singly-linked list.
The problem arises because deleting the current node from a linked list requires modifying the pointer in the previous node -- to which you don't have direct access.
One way to handle this is to use a list with a sentinel (a final node containing a value you recognize as the end of the list). In this case, you can copy the value from the next node into the current node, then delete the next node from the list.
Upvotes: 2
Reputation: 23634
delete nodeUnderEdit;
nodeUnderEdit = nodeUnderEdit->next;
If you delete nodeUnderEdit
first, then nodeUnderEdit->next
will be lost.
You need to first make sure that the node that before nodeUnderEdit's next is connected to nodeUnderEdit->next
, then you can do the remove.
Upvotes: 6