清除单链表

Clearing a singly linked list

本文关键字:链表 单链表 清除      更新时间:2023-10-16

我不知道我的问题在哪里,但我无法清除这个单独链接的列表。我想的都试过了。我正在用一个带有一个元素的列表(实际上是一个链表的哈希表)来测试它,但我无法让我的"erase()"函数工作(它会清理整个列表并删除每个节点)。如果你能看看这个,给我指明正确的方向。

节点结构

struct Node
{
    string m_str;
    Node *m_pNext;
    Node(void) {m_pNext = NULL;}
};
    Node *m_pHead;

擦除功能

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;
    }
}

我的添加功能

void LLString::add (string str)
{
Node *nNode = new Node;
nNode -> m_str = str;
nNode ->m_pNext = m_pHead;
m_pHead = nNode;
}

我目前在这个程序中使用的唯一一个功能是将所有内容发送到文件中。(在擦除功能之前使用)

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();
}

再次,如果你知道为什么删除不起作用,请向我指出。

感谢

简单递归函数:

void erase(Node *n)
{
  if (n)
  {
    erase(n->m_pNext);
    delete(n);
  }
}

问题是,您永远不会让m_pHead为null,因此您的temp也不会为null,而循环永远不会终止并导致双重删除。

我修改了你的代码,看起来很好用。

    void erase (){
    if (!m_pHead)
    {
        return;
    }
    Node *temp = m_pHead;
    while (temp)
    {
        m_pHead = temp->m_pNext;
        delete temp;
        temp = m_pHead;
    }
}
 Node *m_pHead = NULL;

擦除功能:

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;
}