Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have this function to remove nodes that matches a certain criteria in the list. Initially when I wrote it, head node was not deleted if head->value was >= delete_value, but other nodes in the list were deleted, so I decided to write the last if statement to only delete and amend the list if head->value was >= delete_value. It works, but I'm not sure if this is normal?

void remove(List * & head, double value)
{
   if (head == NULL)
   {
    cout << "Empty List";
    return;
   }

   if (head != NULL && head->value != delete_value)
   {
    List* temp1 = head;
    List* temp2 = temp1->next;

       while (temp2 != NULL)
       {
          if (temp2->value >= delete_value)
          {
            List* temp3 = temp2;
            temp2 = temp2->next;
            temp1->next = temp2;
            delete temp3;
          }
          else
          {
            temp1 = temp2;
            temp2 = temp2->next;
          }
       }
   }

   //This deletes head node, if value is greater than or equal to delete_value
   if (head != NULL && head->value >= delete_value)
   {
    List*temp = head;
    head = head->next;
    delete temp;
   }
return;
}
share|improve this question

1 Answer 1

Is this the functionality you are looking for? I'm guessing you are using the STL List here. This will step through the list and remove anything that is greater or equal to the value passed.

template<typename T>
void remove(std::list<T> *l, T value) {
    for (auto it = l->begin(); it != l->end();) {
        if (*it <= value) {
            it = l->erase(it);
        }
        else {
            it++;
        }
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.