清除单链表

时间:2012-02-23 04:25:36

标签: c++ struct linked-list erase

我无法弄清楚我的问题在哪里,但我无法清除这个单链表。我试过了我能想到的一切。我正在测试它带有一个元素的列表(实际上是链接列表的哈希表),但我不能让我的“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();
}

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

由于

3 个答案:

答案 0 :(得分:2)

问题是你永远不要让 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;
    }
}

答案 1 :(得分:2)

简单的递归函数:

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

答案 2 :(得分:0)

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