The sheer amount of code your doing this with is clouding the actual intent.
- You have a linked list of people.
- Given a last name you want to enumerate the list looking for matches.
- Upon discovering a match, you want to prompt the user for deletion confirmation
- If confirmed to delete, extricate the discovered node, leaving the list otherwise-intact, and delete it.
- Else if not confirmed, skip to the next node, looking for more matches
You're apparently having a problem with the deletion portion if the node is, in fact, the head node. Special-cased head-node logic is always tricky for people new to linked lists. Fortunately it can be circumvented entirely if you use the right algorithm. Assuming your list is properly terminated with NULL, including a NULL head pointer if the list is empty, such an algorithm is below:
ListNode ** pp = &head;
while (*pp)
{
if ((*pp)->data.person.getLastName() == answer &&
confirmDelete((*pp)->data.person)) // <== TODO: write this function
{
ListNode *victim = *pp;
*pp = victim->next;
delete victim;
}
else
{ // just advance to next person
pp = &(*pp)->next;
}
}
This will properly delete the user even if they're the first node in the list and properly advance the head pointer for you. It also works on single-node lists both with and without matching conditions, and even empty lists where head
is NULL. This technique uses the pointers in the list as the mechanism for enumerating the list; not just their values, the actual pointers.
Lastly, this can be made considerably more efficient if you keep the list sorted, but I leave that to you.