The purpose of the remove() is to remove the given element from the list. If the
ID: 3680596 • Letter: T
Question
The purpose of the remove() is to remove the given element from the list. If the removal was successful, return true.
The remove() operation is as follows:
// remove(l,d)
// pre: l is a reference to a List // d is a an Element
// post: removes the given element d if it was in the list
// return: true if the element was successfully removed, // false otherwise
bool remove(List *l, Element toRemove)
{
// check error condition first
if (l == NULL)
{
cerr << "Error in remove(List): given a NULL list!"
<< " Returning false, but anything could happen!"
<< endl;
return false;
}
// TODO: complete this function
return false;
}
Explanation / Answer
Here is the code for you:
// remove(l,d)
// pre: l is a reference to a List // d is a an Element
// post: removes the given element d if it was in the list
// return: true if the element was successfully removed, // false otherwise
bool remove(List *l, Element toRemove)
{
// check error condition first
if (l == NULL)
{
cerr << "Error in remove(List): given a NULL list!"
<< " Returning false, but anything could happen!"
<< endl;
return false;
}
// TODO: complete this function
if(l->data == toRemove) //If the current node data is what you should remove.
{
l = l->next; //Just update the reference of List to 2nd element in the list.
return true;
}
while(l->next != NULL) //Moves till the element previous to last element.
if(l->next->data == toRemove) //If the next node data is what you should remove.
{
l->next = l->next->next; //Just bypass the next node, and move on further, which ensures, that it removes the next node.
return true;
}
return false; //If all the conditions fail, i.e., you didn't found the node you are searching for.
}
If you need any refinements, just get back to me.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.