Search code examples
c++structlinked-listerase

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). 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


Solution

  • simple recursive function:

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