gpt4 book ai didi

c++ - 清除单向链表

转载 作者:行者123 更新时间:2023-11-30 02:05:44 26 4
gpt4 key购买 nike

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

关于c++ - 清除单向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9407148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com