c ++链接列表删除所有方法将最后一个元素保留为未删除

时间:2017-03-19 21:30:48

标签: c++ linked-list

我开发了一个从链表中删除所有节点的功能。除最后一个节点外,所有节点都已成功删除。请帮我解释为什么最后一个节点没有被删除?以下是我的代码:

void StudentLinkList::removeAll() {
    StudentData *traversePointer = this->head;

    while (this->head->getNext() != nullptr) {
        this->head = this->head->getNext();
        delete traversePointer;
        traversePointer = this->head;
    }

    delete this->head;
}

2 个答案:

答案 0 :(得分:1)

如此接近

void StudentLinkList::removeAll() {
    StudentData *traversePointer;

    // Continue while there are any elements on the list
    // Extra parens to indicate that we want the result of the 
    // assignment as boolean.  No need to compare to nullptr.
    while ( (traversePointer = this->head) ) {
        // First preserve the rest of the list
        this->head = this->head->getNext();
        // only then can we delete this node
        delete traversePointer;
    }
    // list is now empty
}

答案 1 :(得分:0)

您正在删除此 - > head,但您应将this-> head设置为nullptr。当你释放节点正在使用的内存时,存储在节点旧位置的数据通常不会立即被覆盖,这就是为什么它看起来不会删除最后一个节点。

编辑:正确注意到downvote,有人可以澄清我的错误吗?

此外,我同意上述评论 - 您还应该检查此循环之前此> head是否为空。