从链表中删除偶数C++

fae0ux8s  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(204)

我似乎不明白我错过了什么,我已经花了几个小时,几个小时看着这个,我尝试的一切都不起作用。
我的思维过程是检查列表的第二个节点是否是偶数,如果是,则链接第一个和第三个节点,并删除第二个节点,但它不起作用...我已经在这一周卡住了。

void delete_even()
{
   nod *aux;
   if (head == NULL)
   {
      cout << "List doesn't exist!";
   }
   else
   {
      nod *curent;
      current = head;
      while (curent)
      {
         if (curent->next->info % 2 == 0)
         {
            curent = curent->next->next;
            curent->next = aux;
            delete aux;
            break;
         }
         else
         {
            curent = curent->next;
         }
      } 
   }
}

我不知道还能做什么。

nhjlsmyf

nhjlsmyf1#

这段代码有几处错误。
curent指向列表中的最后一个节点时,使用curent->next会调用 undefined behavior,因为next在这种情况下将是NULL。这会导致您跳过列表中的第一个节点。
您从未将aux赋值为指向任何对象,因此在aux上调用delete也是 undefined behavior
即使aux指向有效节点,您也会在删除aux指向的节点之前将aux分配给curent->next,从而使curent->next指向无效内存,这也是 * 未定义的行为 *。
如果您确实设法从列表中删除了一个节点,那么您将立即中断循环,因此您将只从列表中删除一个偶数,而不是像标题所暗示的那样删除所有偶数。
请尝试以下内容:

void delete_even()
{
   if (!head)
      cout << "List is empty!";
   else
   {
      nod *curent = head, *prev = NULL;
      while (curent)
      {
         nod *next = curent->next;
         if (curent->info % 2 == 0)
         {
            if (prev)
               prev->next = next;
            else
               head = next;
            delete curent;
         }
         else
         {
            prev = curent;
         }
         curent = next;
      }
   }
}

或者:

void delete_even()
{
   if (!head)
      cout << "List is empty!";
   else
   {
      nod *curent = head;
      nod **prev = &head;
      while (curent)
      {
         if (curent->info % 2 == 0)
         {
            *prev = curent->next;
            delete curent;
         }
         else
         {
            prev = &(curent->next);
         }
         curent = *prev;
      }
   }
}

相关问题