1
\$\begingroup\$

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;
}
\$\endgroup\$
  • \$\begingroup\$ It seems to me that this should be a member function of the List class rather than a standalone function. \$\endgroup\$ – Edward Dec 20 '16 at 16:00
2
\$\begingroup\$

I believe these two lines are causing all the trouble.

 List* temp1 = head;
 List* temp2 = temp1->next;

temp2 never gets the head node because it is initialized as head->next to begin with.

I prefer double pointers since I find them rather cleaner.

void remove(Node<ItemType> * & head, double value) {    
    Node<ItemType> **pp = &head;
    Node<ItemType> *curr = head;
    while (curr) {
        if (curr->item == value) {
            *pp = curr->next;
            delete curr;
            curr = *pp;
        }
        else {
            pp = &curr->next;
            curr = curr->next;
        }
    }
}
\$\endgroup\$
1
\$\begingroup\$

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++;
        }
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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