簡體   English   中英

清除單鏈列表

[英]Clearing a singly linked list

我無法弄清楚問題出在哪里,但無法清除此單鏈表。 我已經嘗試了所有我能想到的。 我正在測試一個帶有一個元素的列表(實際上是一個鏈接列表的哈希表),但是我無法使“ 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();
}

再說一次,如果您知道為什么該刪除無法正常工作,請向我指出。

謝謝

問題是您永遠不要讓m_pHead為 null,因此您的溫度也不會為null,而while循環永遠不會終止並導致重復刪除。

我修改了您的代碼,看來工作正常。

    void erase (){
    if (!m_pHead)
    {
        return;
    }

    Node *temp = m_pHead;
    while (temp)
    {
        m_pHead = temp->m_pNext;
        delete temp;
        temp = m_pHead;
    }
}

簡單的遞歸函數:

void erase(Node *n)
{
  if (n)
  {
    erase(n->m_pNext);
    delete(n);
  }
}
 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM