我想在C ++中实现单个链表。我有一个细分错误问题。我认为这是添加功能的问题。谁能检查并说我该如何改善?
#include <iostream>
class T
{
private:
float t;
public:
T *next;
T()
{
this->t = 0.0;
this->next = NULL;
}
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();
}
};
int main()
{
MyList ml;
T a,b,c;
ml.add_T(&a);
ml.add_T(&b);
ml.add_T(&c);
ml.print();
return 0;
}
正如评论所说,您无条件地取消引用head
,这会调用未定义的行为。由于要在头上添加节点,因此可以简单地执行以下操作: