0

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"))
		{
			ptrCurrent->Show();
			ptrDelete = ptrCurrent;
			ptrCurrent = ptrCurrent->ptrNext;
			delete ptrDelete;
		}
		else
		{
			ptrCurrent = ptrCurrent->ptrNext;
		}
	}

	cout << "\nTrainees Sacked!";
2
Contributors
3
Replies
4
Views
12 Years
Discussion Span
Last Post by Chainsaw
0

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

0

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

You have a list like this:

head-->first-->second-->third-->last

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)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.