我正在尝试删除整个链接列表,但却出现了分段错误,无法检测出真正的问题。当我尝试使用gdb进行调试时,它能够删除第一个节点,但在删除第二个节点时抛出分段错误。请告诉我可能的原因。
#include <iostream>
using namespace std;
class listNode
{
public:
listNode *next;
char data;
listNode ()
{
next = NULL;
data = '\0';
}
listNode (char alphabet)
{
next = NULL;
data = alphabet;
}
~listNode ()
{
delete next;
}
};
class linkedList
{
public:
listNode *head;
void insert (listNode * node);
trieNode *search (char alphabet);
linkedList ();
~linkedList ();
void printList ();
private:
void deleteCompleteList ();
};
int
main ()
{
linkedList testList;
for (int i = 0; i < 10; i++)
{
listNode *temp = new listNode ('a' + i);
testList.insert (temp);
}
testList.printList ();
}
linkedList::linkedList ()
{
linkedList::head = NULL;
}
linkedList::~linkedList ()
{
linkedList::deleteCompleteList ();
}
void
linkedList::printList ()
{
listNode *temp = head;
while ( temp )
{
cout << temp->data << endl;
temp = temp->next;
}
}
void
linkedList::insert (listNode *node)
{
node->next = head;
head = node;
}
trieNode *
linkedList::search (char alphabet)
{
listNode *temp = head;
while (temp)
{
if (temp->data == alphabet)
return temp->down;
temp = temp->next;
}
return NULL;
}
void
linkedList::deleteCompleteList ()
{
listNode *temp ;
while ( head )
{
temp = head;
head = head->next;
delete temp;
}
}
答案 0 :(得分:4)
因为在listNode d'tor中它正在删除下一个节点。因此,当它删除列表中的第二个节点时,它已被删除。
~listNode ()
{
delete next;
}
将其更改为...
~listNode ()
{
}
答案 1 :(得分:1)
您要删除head->next
两次;一次在listNode
析构函数中,一次在循环中。