My code to delete nodes of a linked list works fine, but it crashes when I try to delete something that is not on the list. The cout statement wont even show
// in main()
while (toupper(answer) == 'Y')
{
system("cls");
cout << "Enter ID: ";
cin >> id;
list.deleteNode(head, id);
cout << "Delete an Employee record? (Y/N) ";
cin >> answer;
}
// in Employee.cpp
void Employee::deleteNode(Employee *&head, int id)
{
Employee *lead = head;
Employee *follow = head;
while ((id != lead->id) && (lead != NULL))
{
follow = lead;
lead = lead->next;
}
if (lead == head) // Check to see if it is at the head of the list
{
head = head->next;
delete lead;
}
elseif (lead->next == NULL) // Check to see if it is the last node
{
follow->next = NULL;
delete lead;
}
elseif (lead == NULL)
cout << "Not in the list" << endl;
else
{
follow->next = lead->next;
delete lead;
}
}