清除单链表
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();
}
再次,如果你知道为什么删除不起作用,请向我指出。
感谢
简单递归函数:
void erase(Node *n)
{
if (n)
{
erase(n->m_pNext);
delete(n);
}
}
问题是,您永远不会让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;
}
}
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;
}
相关文章:
- 如何找到2个单链表的公共节点
- 对单链表的混淆
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 在单链表前面添加一个节点后,我无法遍历每个节点
- 具有完整五法则的简单链表
- 在 C++ 中实现简单链表时出现问题,没有输出
- 在析构函数中删除单链表的正确方法是什么?
- 移动语义 c++ 单链表
- 单链表时间
- 带有unique_ptr的通用单链表,MS visual studio C++中存在未知错误
- 使用 std::unique_ptr 的通用单链表,Visual Studio C++ Microsoft中存在未知的反
- 删除单链表列表
- 在单链表中的后端插入节点
- 合并单链表上的排序
- 简单链表与下一个>下一个交换
- 我试图键入一个函数来在单链表的末尾添加一个节点,但不起作用
- 单链表分配问题 (nullptr)
- 如何将单链表更改为双链表
- 如何制作一个函数,只需更改链接即可交换单链表中的两个相邻元素
- 从单链表到双链表的变化