Share
Explore BrainMass

Erase all occurrences of a target in linked list

Extend the function eraseValue() to erase all occurrences of "target" in the linked list.

template < typename T >
void eraseAll (node * & front, const T& target);

This is the implementation of eraseValue() that must be modified.

{
node< T > *curr = front, *prev = NULL;
bool foundItem = false;

while (curr != NULL && !foundItem )
{
if (curr->nodeValue == target)
{
if (prev == NULL)
{
front = front -> next;
}
else
{
prev->next = curr-> next;
delete curr;
foundItem = true;
}
}
else
{
prev = curr;
curr = curr-> next;
}
}

Solution Preview

To erase all occurences of "target" in the linked list, you need to make following modifications to the given code.

1. Change "while (curr != NULL && !foundItem )" to "while (curr != NULL)" so that entire linked list is scanned for target value, rather than just stopping after finding first ...

Solution Summary

The solution first mentions what needs to be modified in eraseValue function to extend it to eraseAll function, and then gives the code for eraseAll function.

$2.19