【问题标题】:Clearing a singly linked list清除单链表
【发布时间】:2012-02-23 04:25:35
【问题描述】:

我不知道我的问题出在哪里,但我无法清除这个单链表。我已经尝试了我能想到的一切。我正在用一个包含一个元素的列表(实际上是一个链表的哈希表)对其进行测试,但我无法让我的“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();
}

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

谢谢

【问题讨论】:

    标签: c++ struct linked-list erase


    【解决方案1】:

    简单的递归函数:

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

    【讨论】:

    • 你的意思是有一个else 而不是if 之外的一个声明吗?就目前而言,您唯一会打电话给delete 的人是NULL
    【解决方案2】:

    问题是你永远不会让 m_pHead 为空,所以你的 temp 也不会为空,while 循环永远不会终止并导致双重删除。

    我修改了您的代码,似乎可以正常工作。

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

    【讨论】:

    • 这就是我最初的代码,但它给出了以下错误 --- hw5_hash.exe 中 0x010f9531 处的未处理异常:0xC0000005:访问冲突读取位置 0xfdfdfe1d。 --- 它开始编译但停在这一行 -- m_pHead = temp->m_pNext; -- 你知道是什么原因造成的吗?
    【解决方案3】:
     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;
    }
    

    【讨论】:

    • 在 - while (temp-> m_pNext != NULL) 时仍然出现同样的错误 - 它不允许我检查 temp-> m_pNext。我不知道为什么。
    • 我认为代码中没有任何错误,它一定是代码以外的东西。你用的是什么编译器?
    • 尝试将其实现为类而不是结构。这不是一个解决方案,而只是一个尝试不同事物的建议。
    • 或者写一个删除函数,删除一个节点,看看它是否有效,然后尝试重复调用它来擦除所有节点。
    • 在使用 Visual Studio 2010 Ultimate 的 Windows 电脑上打开。我想知道同样的事情。我尝试修复程序并进行更新和一切,但没有运气。我想这是我必须自己解决的问题。再次感谢大家帮助我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 2015-12-08
    • 1970-01-01
    • 2019-02-26
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多