template <typename T>
void LinkedList<T>::clear()
{
LinkedList* p = this;
LinkedList* q = this;
while(p->m_next != NULL)
{
p = p->m_next;
delete q;
q = p;
}
return;
}
class LinkedList
{
public:
T m_data; // Data to be stored
LinkedList<T>* m_next; // Pointer to the next element in the list
//Continues into function declarations.
// . . .
};
这些是我认为相关的代码片段,如果您需要更多信息,请告诉我。
问题:一旦我击中删除 q 的行,我就会出现段错误
delete q;
我插了一些
cerr << "msg" << endl;
只是为了检查。关于如何更改此代码以停止段错误的任何想法?显然我正在删除我不应该删除的内容,但我不知道如何删除。clear 函数的要点是把单链表除结束哨兵外完全删除。这个 while 循环总是在第一次运行时出现故障。
这是测试这个的代码。
void test01() {
LinkedList < int > A;
cout << endl << endl;
cout << " ***************** " << endl;
cout << " * TEST SET #1 * " << endl;
cout << " ***************** " << endl;
cout << "Is the list empty? " << boolalpha << A.isEmpty() <<endl;
cout << A << endl;
cout << "Size of A = " << A.size() << endl;
//TEST : Inserting 10 numbers to a
cout << endl << "TEST : Inserting 10 numbers to A" << endl;
for (int k=0; k<10; k++){
A.insert_front(k+1);
}
cout << A << endl;
cout << "Size of a = " << A.size() << endl;
//TEST : Clearing A
cout << endl << "TEST : Clearing A" << endl;
A.clear();
cout << A << endl;
cout << "Size of A = " << A.size() << endl << endl;
cout << "Test 01 - Done!" << endl;
} // Destructor Called Here!!
我只是将功能更改为
template <typename T>
void LinkedList<T>::clear()
{
LinkedList* p = this;
LinkedList* q = this;
if(p->m_next != NULL)
{
p = p->m_next;
q = q->m_next;
}
while(p->m_next != NULL)
{
q = p;
p = p->m_next;
delete q;
}
m_next = NULL;
return;
}
现在工作。