C++ Circular Link List - 删除所有节点
C++ Circular Link List - remove all nodes
我正在尝试删除单循环链表中的所有节点。但是我得到了以下错误:
malloc: *** error for object 0x1005068f0: pointer being freed was not allocated
函数如下:
void StudentLinkList::removeAll() {
StudentData *traversePointer = this->head;
while (this->head != nullptr) {
this->head = this->head->getNext();
delete traversePointer;
traversePointer = nullptr;
traversePointer = this->head;
this->size--;
}
}
我在这一行遇到错误:
delete traversePointer;
我的问题是,为什么错误中显示的 while 循环中没有分配 traversePointer?
时间应该是:
while(this->size){
当循环完成后,设置this->head = nullptr。循环中不需要设置traversePoitner = nullptr
替代版本(我还没有确认这一点),不依赖于 this->size 是正确的,只是列表是循环的:
void StudentLinkList::removeAll() {
if(this->head == nullptr)
return;
StudentData *traversePointer = this->head;
StudentData *deletePointer;
do{
deletePointer = traversePointer;
traversePointer = traversePointer->getNext();
delete deletePointer;
}while(traversePointer != this->head);
this->head = nullptr;
this->size = 0;
}
我正在尝试删除单循环链表中的所有节点。但是我得到了以下错误:
malloc: *** error for object 0x1005068f0: pointer being freed was not allocated
函数如下:
void StudentLinkList::removeAll() {
StudentData *traversePointer = this->head;
while (this->head != nullptr) {
this->head = this->head->getNext();
delete traversePointer;
traversePointer = nullptr;
traversePointer = this->head;
this->size--;
}
}
我在这一行遇到错误:
delete traversePointer;
我的问题是,为什么错误中显示的 while 循环中没有分配 traversePointer?
时间应该是:
while(this->size){
当循环完成后,设置this->head = nullptr。循环中不需要设置traversePoitner = nullptr
替代版本(我还没有确认这一点),不依赖于 this->size 是正确的,只是列表是循环的:
void StudentLinkList::removeAll() {
if(this->head == nullptr)
return;
StudentData *traversePointer = this->head;
StudentData *deletePointer;
do{
deletePointer = traversePointer;
traversePointer = traversePointer->getNext();
delete deletePointer;
}while(traversePointer != this->head);
this->head = nullptr;
this->size = 0;
}