gpt4 book ai didi

c++ - 从自定义链表中删除一个值

转载 作者:太空宇宙 更新时间:2023-11-04 11:43:24 24 4
gpt4 key购买 nike

int SDI::LinkedList::removeValue(int removeValue)
{
SDI::Node* current = head;
SDI::Node* prev = head;
while (current != nullptr)
{
if (current == head)
{
if (current->value == removeValue)
{
current = current->next; // track the next value
delete head;
head = current-> next;
return 1;
}

}
else
{
if (current->value != removeValue)
{
prev = current; /// don’t lose track of the previous value, saves working 1 ahead
current = current-> next; // let the loop deal with it

}
else
{
prev->next = current->next;
delete current;
}
if (current->next != nullptr)
{
if (current->next->value == removeValue)
{
SDI::Node* temp = current->next;
current->next = current->next->next;
delete temp;
return 1;
}
}
}
}
return 0;
}

一切似乎都很好,直到它到达线:

"if (current->value != removeValue)"

它似乎只是直接跳过它,但 current-> value 不等于 removeValue,如 watcher 中所示。

最佳答案

看起来你有一个无限循环 if current->value != removeValue 在循环的第一次迭代中你永远不会离开 if (current == head) 条件,因为当前永远不会更新。如果您将第一个条件从 if (current == head) 更改为 if (current == head && current->value == removeValue) 它现在应该正确地到达current->value != removeValue 您所说的被跳过的条件。

如果没有关于您的程序似乎跳过的步骤的更多详细信息,我没有看到除此之外的任何其他错误。

关于c++ - 从自定义链表中删除一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20572123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com