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)"
它似乎只是直接跳过它,但是当前 - >值不等于removeValue,如观察者所示。
答案 0 :(得分:1)
如果你在循环的第一次迭代中current->value != removeValue
,你似乎有一个无限循环,因为你永远不会离开if (current == head)
条件,因为当前永远不会更新。如果您将第一个条件从if (current == head)
更改为if (current == head && current->value == removeValue)
,则现在应该正确地达到您所说的被跳过的current->value != removeValue
条件。
如果没有关于程序似乎跳过的步骤的详细信息,我就不会发现任何其他错误。