我目前正在创建一个双向链接的人员及其信息列表。其中一个要求是不仅要从列表中删除某个人,还要返回指向已删除人员的指针。我创建了一个可以返回的Person*
指针。目前,这是通过基本上创建一个深拷贝并在删除原始文件时返回副本来完成的。如何在不导致内存泄漏的情况下返回此指针?
Person * AddressList::Delete(const char * fname, const char * lname)
{
bool found = false;
Node * travel = m_head;
Node * trail = nullptr;
Person * retper = nullptr;
if (m_head != nullptr)
{
if (strcmp(lname, travel->GetPerson()->GetLName()) == 0 && strcmp(fname, travel->GetPerson()->GetFName()) == 0)
{
found = true;
retper = new Person(*m_head->GetPerson());
travel = m_head->GetNext();
delete m_head;
m_head = travel;
}
else
{
while (travel != nullptr)
{
if (strcmp(lname, travel->GetPerson()->GetLName()) == 0 && strcmp(fname, travel->GetPerson()->GetFName()) == 0)
{
found = true;
retper = new Person(*travel->GetPerson());
trail->SetNext(travel->GetNext());
delete travel;
travel = nullptr;
}
else if (travel != nullptr)
{
trail = travel;
travel = travel->GetNext();
}
}
}
}
if (found == false)
{
cout << "Person not found." << endl;
}
else
{
if (m_head != nullptr)
{
trail = nullptr;
travel = m_head;
travel->SetPrev(nullptr);
while (travel->GetNext() != nullptr)
{
trail = travel;
travel = travel->GetNext();
travel->SetPrev(trail);
}
m_tail = travel;
}
else
{
m_tail = nullptr;
}
m_nextR = m_tail;
m_next = m_head;
m_length--;
}
return retper;
}