C++链表删除整个列表,而不是仅删除一个节点



我创建了一个名为ScanList的链表,其中包含对象Scan的节点。但是当我从链接列表中删除第一个扫描并关闭程序时,我得到一个类型为"的异常;访问违规读取位置";在ScanList的析构函数中。

从"扫描列表"中删除"扫描"的功能如下。

bool ScanList::removeScan(int serialNumber)
{// post: IF serialNumber is present in the list 
// THEN scan has been removed from it and true has been returned 
// ELSE false has been returned 
Scan* currentScan = scans;
Scan* previousScan = scans;
if (currentScan != NULL && currentScan->getSerialNumber() == serialNumber)
{ // if serialNumber is the first element of the linked list
*scans = currentScan->getNext();
delete currentScan;
return true;
}
while (currentScan != NULL && currentScan->getSerialNumber() != serialNumber)
{
*previousScan = currentScan;
currentScan = currentScan->getNext();
}
if (currentScan == NULL)
{ // serialNumber is not present in the list
return false;
}
// serialNumber is present in the list and is removed
previousScan->setNext(currentScan->getNext());
delete currentScan;
return true;
}

我使用Copy赋值运算符,但即使这样它也会删除扫描。它确实返回了正确的值,但当我删除currentScan时,它也会删除ScanList的整个Scan*扫描。这是我的复印作业操作员。

Scan* Scan::operator=(const Scan* scan)
{
// check if the Scan on the left is the same as Scan on the right
if (this == scan)
{ // if they are the same, go out of the function and return
return this;
}
this->serialNumber = scan->serialNumber;
this->timesRecycled = scan->timesRecycled;
this->next = scan->next;
return this;
}

有人能告诉我我做错了什么吗?

问题已经解决,我删除了扫描析构函数中每个扫描的nextScan,导致整个列表被删除。谢谢你的建议!

相关内容

  • 没有找到相关文章

最新更新