[英]Clearing a singly linked list
I can not figure out where my problem is but I am not able to clear this singly linked list. 我无法弄清楚问题出在哪里,但无法清除此单链表。 I have tried about everything I can think of.
我已经尝试了所有我能想到的。 I am testing it with a list with one element (well actually a hash table of linked lists) but I can't get my "erase()" function to work (it would clean the entire list and delete each node).
我正在测试一个带有一个元素的列表(实际上是一个链接列表的哈希表),但是我无法使“ erase()”函数正常工作(它将清理整个列表并删除每个节点)。 If you can take a look at this and point me in the right direction.
如果您可以看一下,并指出正确的方向。
The Node Structure 节点结构
struct Node
{
string m_str;
Node *m_pNext;
Node(void) {m_pNext = NULL;}
};
Node *m_pHead;
The erase function 擦除功能
Void LLString::erase (void){
if (!m_pHead)
{
return;
}
Node *temp = m_pHead;
while (temp)
{
temp = m_pHead; // The error allways shoes up around her
if (temp->m_pNext) // It has moved around a little as I have tried
{ // different things. It is an unhanded exception
m_pHead = temp->m_pNext;
}
temp->m_pNext = NULL;
delete temp;
}
}
My add function 我的添加功能
void LLString::add (string str)
{
Node *nNode = new Node;
nNode -> m_str = str;
nNode ->m_pNext = m_pHead;
m_pHead = nNode;
}
And the only other function I am currently using with the program is this function sending everything to a file. 我当前在程序中使用的唯一其他功能是该功能将所有内容发送到文件。 (used right before the erase function)
(在擦除功能之前使用)
void LLString::toFile (void)
{
ofstream fout;
fout.open ("stringData.txt",ios::app);
Node* temp = m_pHead;
while (temp)
{
fout << temp->m_str << endl;
temp = temp->m_pNext;
}
fout.close();
}
Again if you have any idea why that delete isn't working please point it out to me. 再说一次,如果您知道为什么该删除无法正常工作,请向我指出。
Thanks 谢谢
problem is that you never let m_pHead null so your temp is also don't get null and while loop never terminate and cause double deletion. 问题是您永远不要让m_pHead为 null,因此您的温度也不会为null,而while循环永远不会终止并导致重复删除。
I modified your code, which seems to work fine. 我修改了您的代码,看来工作正常。
void erase (){
if (!m_pHead)
{
return;
}
Node *temp = m_pHead;
while (temp)
{
m_pHead = temp->m_pNext;
delete temp;
temp = m_pHead;
}
}
simple recursive function: 简单的递归函数:
void erase(Node *n)
{
if (n)
{
erase(n->m_pNext);
delete(n);
}
}
Node *m_pHead = NULL;
The erase function: 擦除功能:
Void LLString::erase (void)
{
if (m_pHead==NULL)
{
return;
}
Node *temp = m_pHead;
while (temp->m_pnext!=NULL)
{
m_pHead = temp->m_pNext;
delete temp;
temp = m_pHead;
}
delete temp;
m_pHead = NULL;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.