bool Ordered_ list::remove(int data){if(list == NULL) return false;//if head nod
ID: 3787073 • Letter: B
Question
bool Ordered_ list::remove(int data){if(list == NULL) return false;//if head node is has data equal to data then forward head if(list rightarrow data == data){node *temp = list; list = list rightarrow next; delete temp; return true;}else{node *temp = list; while(temp rightarrow next != NULL){if(temp rightarrow next rightarrow data == data){ //if temp next data is equal to data then remove it node *temp = temp rightarrow next; temp rightarrow next = temp rightarrow next rightarrow next; delete temp; return true;} temp = temp rightarrow next;} return false;// data is not available in list}}Explanation / Answer
Here is the modified code for you:
bool Ordered_list::remove(int data)
{
if(list == NULL) //If the list is empty.
return false; //Conclude node is not in the list.
if(list->data == data) //If the first element is what your search key is.
{
node *temp = list; //Make temp point to the first node.
list = list->next; //Make the list bypass the first node.
delete temp; //Remove the bypassed node, which was pointed by temp;
return true; //Conclude the node has been deleted.
}
else //If the list is neither empty, not the first element is the search key.
//i.e., the search key could be found in the list further or the key is not found.
{
node *temp = list; //Make temp point to the first node in the list.
while(temp->next != NULL) //While there is next node to still move further.
{
if(temp->next->data == data) //If the next node is holding the search key.
{
node *toDelete = temp->next; //This should be where you're failing. You're declaring another variable temp with the same name.
//Make toDelete to point to the next node, i.e., the node to be deleted.
temp->next = temp->next->next; //Bypass the next node, and connect further node.
delete toDelete; //Remove the bypassed node, which was pointed by toDelete.
return true; //Conclude the node has been deleted.
}
}
return false; //If all the conditions fail, conclude the node is not in the list.
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.