【发布时间】:2020-05-16 20:39:22
【问题描述】:
我试图实现一个单链表。但是,我对搜索和删除功能有疑问。我遇到分段错误,我不知道为什么。有人可以解释我,我做错了什么,以及如何改进这个代码工作?谢谢你
#include <iostream>
class T
{
private:
float t;
public:
T *next;
T()
{
this->t = 0.0;
this->next = NULL;
}
float getT()
{
return this->t;
}
T(float t, T* next)
{
this->t = t;
this->next = next;
}
T(const T& tx)
{
this->t = tx.t;
this->next = tx.next;
}
void print()
{
std::cout << this->t << "\n";
}
};
class MyList
{
private:
T *head;
public:
T* add_T(T *x)
{
T *new_head = new T(*head);
new_head -> next = head;
head = new_head;
return head;
}
void print()
{
for(T *curr = head; curr != NULL; curr = curr->next)
curr->print();
}
void delete_all()
{
T *x = head;
while (x!= NULL)
{
head = head->next;
delete x;
x = head;
}
head = NULL;
}
T * search_val(T * k)
{
if (this->head == NULL)
return NULL;
if (this->head->getT() == k->getT())
return this->head;
return search_val(this->head->next);
}
};
int main()
{
MyList ml;
T a,b,c;
ml.add_T(&a);
ml.add_T(&b);
ml.add_T(&c);
ml.print();
T *y = new T(3.14, NULL);
T *x = ml.search_val(y);
ml.delete_all();
delete x,y;
return 0;
}
【问题讨论】:
-
哪一行触发了分段错误?
-
我以为这个代码是在上周修复的。 https://stackoverflow.com/questions/61700490/single-linked-list-c-segmentation-fault-add-to-list-print 我不确定为什么带有未初始化头指针的
T* add_T(T *x)的错误实现又回来了。
标签: c++ linked-list segmentation-fault singly-linked-list