I've got a singly linked list, and the following code is supposed to delete all nodes that are ranked as "Trainee", it deletes them all, but if the last node is a "Trainee", it will not delete it, why is that?

void LinkedList::removeLowest()
	Soldier * ptrDelete;
	ptrCurrent = ptrHead;
	while(ptrCurrent != NULL)
		if(!strcmp(ptrCurrent->getRank(), "Trainee"))
			ptrDelete = ptrCurrent;
			ptrCurrent = ptrCurrent->ptrNext;
			delete ptrDelete;
			ptrCurrent = ptrCurrent->ptrNext;

	cout << "\nTrainees Sacked!";

Recommended Answers

All 3 Replies

Because you don't update ptrHead. If you delete the last node, ptrHead should become NULL.

but ptrHead just points to the first node in the list, setting it to NULL would delete that node

Sorry, I misunderstood; I thought you meant Last as in "last remaining".

You have a list like this:


and you want to delete second because she is a trainee.

your code does this:

ptrCurrent points to second
show second
set ptrCurrent to point to third
delete second

Unless the destructor does some work on the entire list, you have this list:

head-->first-->[deleted second]-->third-->last

1) Does the destructor move first's next pointer to point to third (second's next)?

2) If you delete 'first', who updates the head pointer to point to first's next pointer?

3) If you delete 'last' does third get updated to point to null (last's next)? (note this would work fine if (1) works fine, I think)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.