C++链表删除结点释放内存问题
boolLinearList::remove(constintdata){NODEcurr;NODEprev;if(isEmpty()){std::cout<<"cann...
bool LinearList::remove(const int data)
{
NODE curr;
NODE prev;
if (isEmpty())
{
std::cout << "can not remove! EMPTY!" << std::endl;
return false;
}
else if (_first->data == data)
{
curr = _first;
_first = _first->next;
delete curr;
_length--;
return true;
}
else
{
for (curr = _first, prev = NULL;
curr != NULL; prev = curr, curr = curr->next)
{
if (curr->data == data)
{
prev->next = curr->next;
_length--;
}
}
delete curr;//会存在内存泄露
return true;
}
}
若链表是这样的1,2,3,2 我删除值为2的结点,用一次remove(2),但是只有最后一个2的内存会被释放,
怎么释放第二个位置的2? 展开
{
NODE curr;
NODE prev;
if (isEmpty())
{
std::cout << "can not remove! EMPTY!" << std::endl;
return false;
}
else if (_first->data == data)
{
curr = _first;
_first = _first->next;
delete curr;
_length--;
return true;
}
else
{
for (curr = _first, prev = NULL;
curr != NULL; prev = curr, curr = curr->next)
{
if (curr->data == data)
{
prev->next = curr->next;
_length--;
}
}
delete curr;//会存在内存泄露
return true;
}
}
若链表是这样的1,2,3,2 我删除值为2的结点,用一次remove(2),但是只有最后一个2的内存会被释放,
怎么释放第二个位置的2? 展开
1个回答
展开全部
bool LinearList::remove(const int data)
{
NODE curr;
NODE prev;
if (isEmpty())
{
std::cout << "can not remove! EMPTY!" << std::endl;
return false;
}
else if (_first->data == data)
{
curr = _first;
_first = _first->next;
delete curr;
_length--;
return true; //<---这里有问题,如果第一个节点符合条件,删除后会跳退函数
//不再查找后面符合条件的节点,从你的问题来看,似乎
//想把链表中所有符合条件的节点都删了
}
else
{
for (curr = _first, prev = NULL;
curr != NULL; prev = curr, curr = curr->next)
// 不能直接用curr=curr->next循环赋值,否则当curr被释放后,
// curr->next引用会出错.
{
if (curr->data == data)
{
prev->next = curr->next;
// 在使用prev指针前必须判断它是否为NULL,否则会出现运行时错误
_length--;
// <----这里有问题,找到符合条件的节点没有对应的删除操作
}
}
// <---这里必须添加一行判断,如果不为NULL才能释放
delete curr; // 否则会出现释放NULL指针出错
return true;
}
}
// 修正如下,没有测试,请自行调试:
bool LinearList::remove(const int data)
{
NODE curr;
NODE prev;
bool bRet = false;
if (isEmpty())
{
std::cout << "can not remove! EMPTY!" << std::endl;
return bRet;
}
else
{
for (curr = _first, prev = NULL;
curr != NULL; )
{
if (curr->data == data)
{
if (curr == _first ) _first = curr ->next;
if (prev != NULL ) prev->next = curr->next;
_length--;
delete curr;
bRet = true;
if (prev != NULL ) curr = prev->next;
else curr = _first;
}
else
{
prev = curr;
curr = curr->next;
}
}
}
return bRet;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询