Linked list and delete code

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 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;
	}

	else if (lead->next == NULL)		// Check to see if it is the last node
	{
		follow->next = NULL;
		delete lead;
	}
	else if (lead == NULL)
		cout << "Not in the list" << endl;
	else
	{
		follow->next = lead->next;
		delete lead;
	}
}



i appreciate the help
ptrs suck
help... anybody...
On line 19 you do access lead->id before you know that lead is not null.
On line 31 you again access member before verifying (line 36) non-nullness.

Reorder tests.
Topic archived. No new replies allowed.