954,219 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Why doesn't this remove the last node in a linked list?

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!";
paynekiller
Newbie Poster
6 posts since Aug 2004
Reputation Points: 10
Solved Threads: 0
 

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

Chainsaw
Posting Pro in Training
436 posts since Jun 2004
Reputation Points: 36
Solved Threads: 11
 

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

paynekiller
Newbie Poster
6 posts since Aug 2004
Reputation Points: 10
Solved Threads: 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)

Chainsaw
Posting Pro in Training
436 posts since Jun 2004
Reputation Points: 36
Solved Threads: 11
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You