我正在尝试从双向链表中删除所有偶数。
我认为这些案件是:
以下代码无效:
void DoublyList::deleteEvens()
{
if (first == NULL) {
cerr << "Empty List" << endl;
}
else {
Node *current = first;
bool found = false;
while (current != NULL && (!found)) {
Node *tCurrent = current;
if (current->getNextLink() == NULL) {
if (current->getData() % 2 == 0) {
first = NULL;
last = NULL;
delete current;
current = NULL;
count = 0;
}
else {
cerr << "Not in the list" << endl;
found = true;
}
}
else if (current == first && current->getData() % 2 == 0) {
first = first -> getNextLink();
first->setPreviousLink(NULL);
current = current->getNextLink();
delete tCurrent;
tCurrent = NULL;
-- count;
}
else if (current == last && current->getData() % 2 == 0) {
last = last->getPreviousLink();
last->setNextLink(NULL);
delete current;
current = NULL;
-- count;
}
else if (current->getData() % 2 == 0) {
current->getPreviousLink()->setNextLink(current->getNextLink());
current->getNextLink()->setPreviousLink(current->getPreviousLink());
current = current->getNextLink();
delete tCurrent;
tCurrent = NULL;
}
else {
current = current->getNextLink();
}
}
}
}
答案 0 :(得分:3)
问题似乎是您的第一个案例:current->getNextLink() == NULL
将对列表中的最后一项评估为true。因此,当您处理最后一项时,您实际上会删除整个列表。
我认为这是为了检测列表中的第一项,将其更改为:
if (current->getNextLink() == NULL && current->getPreviousLink() == NULL)
或者,将它移到循环之外,只使用第一个变量。