0

我正在尝试从链接列表中删除。但如果我尝试删除第一个元素,它似乎不起作用。

if (found)
{
    if (prev == NULL)
    {
        prev = head;
        prev -> next = curr -> next;
        delete curr;
    }
    else
    {
        prev -> next = curr -> next;
        delete curr;
    }
}

return found;

如果我要从中间或尾部的某处删除,findNode 函数会起作用。但我发现如果我从尾部删除,我必须将 next 设置为 NULL,对吗?

4

2 回答 2

1

问题可能是您实际上并没有将 to 更改head为指向列表的新头部。你必须改变head

if (prev == NULL)
{
    head = head->next;  // Set `head` to point to the next node, i.e. the new `head`
    delete curr;
}
于 2013-02-14T17:43:19.793 回答
0

假设这findNode是正确的并且设置prev为之前的节点curr(可能要考虑一个双向链表)然后

   if (prev == NULL)
   {
      prev = head;
      prev -> next = curr -> next;
      delete curr;
   }

是不正确的。由于何时prev为 NULL,所以找到的就是头节点。

所以代码应该是

   if (prev == NULL)
   {
      head = head->next;
      delete curr;
   }
于 2013-02-14T17:45:39.023 回答