我无法理解为什么当我创建两个或更多节点时(如下所示),函数 void del_end()
只会删除 char name[20]
而不是整个节点。如何在不发生内存泄漏的情况下解决此问题?
#include <iostream>
using namespace std;
struct node
{
char name[20];
char profession[20];
int age;
node *nxt;
node *prv;
};
node *start_ptr = NULL;
void del_end()
{
node *temp, *temp2;
temp = start_ptr;
if (start_ptr == NULL)
cout << "Can't delete: there are no nodes" << endl;
else if (start_ptr != NULL && start_ptr->nxt == NULL)
{start_ptr=NULL;}
else
{
while (temp->nxt != NULL)
{
temp = temp->nxt;
}
temp2=temp->prv;
delete temp;
temp->nxt= NULL;
}
}
最佳答案
你的代码有一些问题,最糟糕的是:
temp2=temp->prv;
delete temp2;
temp->nxt= NULL;
您要删除倒数第二个节点,使指向它的所有指针悬空,并丢失最后一个节点。
但如果您发布更多真实代码,我们可以告诉您更多信息。
编辑:
这是 del_end
的稍微清理过的版本(仍然有很大的改进空间)。
void del_end()
{
if (start_ptr == NULL)
{
cout << "Can't delete: there are no nodes" << endl;
return;
}
if (start_ptr->nxt == NULL)
{
delete start_ptr;
start_ptr = NULL;
return;
}
node *nextToLast = start_ptr;
node *last = start_ptr->nxt;
while(last->nxt != NULL)
{
nextToLast = last;
last = last->nxt;
}
delete last;
nextToLast->nxt = NULL;
return;
}
请注意,这不假定prev
链接是正确的,这在这里似乎很谨慎。
关于c++ - 删除双向链表中的节点 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3189202/