C ++:While循环不在链接列表中工作

时间:2015-10-16 03:33:22

标签: c++ c++11

我正在尝试从简单的链接列表中移除项目(使用nextvalue)。

删除所有实例。抱歉错误

到目前为止,这是我的代码,但它似乎只有一个只包含nullptr的链接列表

我在这里做错了什么?

void remove(node<int>*& list1, int val)
{
    while (list1 != nullptr)
    {
        if (list1->value == val)
        {
            node<int>* removed = list1;
            list1 = list1->next;
            delete removed;
        }
        else
            list1 = list1->next;
    }
}

2 个答案:

答案 0 :(得分:0)

  

到目前为止,这是我的代码,但它似乎只有一个只包含nullptr的链表:

这是因为list1是通过引用传递的,而您正在更改其值,直到它等于nullptr

这是修复它的一种方法。

void remove (node<int>*& list1, int val) {

   // If the head of the list contains the value,
   // change the head to point to the next element.
   if(list1->value == val) {
      node<int>* removed = list1;
      list1 = list1->next;
      delete removed;
      return;
   }

   node<int>* prev = list1;
   node<int>* iter = list1;

   // Look for the val in the list
   // Delete the node that has the value.
   // Fix the links.
   while ( iter != nullptr ) {
      if(iter->value == val) {
         prev->next = iter->next;
         delete iter;
         return;
      }
      prev = iter;
      iter = iter->next;
   }
}

答案 1 :(得分:0)

在迭代时修改参数值是个不错的主意,试试这个:

void remove (node<int>*& head, int val) {
    //empty case
    if(head==nullptr)
        return;
    // front remove - need to reassign head
    if(head->value == val) {
        node<int>* removed = head;
        head = head->next;
        delete removed;
        return; // if you need to delete the first occurence
    }
    // other cases - just jook forward
    node<int>* curr = head;
    while(curr->next != nullptr){
        if(curr->next->value == val){
            node<int>* removed = curr->next;
            curr->next = curr->next->next;
            delete removed;
            return; // if you need to delete the first occurence
        }
        curr = curr->next;
    }
}