我想在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;
}
编辑:
仍然不是我想要的,因为我从头节点看到0。
#include <iostream>
class T
{
private:
float t;
public:
T *next;
T()
{
this->t = 0.0;
this->next = NULL;
}
T(float t)
{
this->t = t;
}
T(float t, T* next)
{
this->t = t;
this->next = next;
}
T(const T& tx)
{
this->t = tx.t;
this->next = tx.next;
}
float getT()
{
return this->t;
}
void print()
{
std::cout << this->t << "\n";
}
};
class MyList
{
private:
T *head;
public:
MyList()
{
head = new T();
}
T* add_T(T *x)
{
head = new T(x->getT(), head);
return head;
}
void print()
{
for(T *curr = head; curr != NULL; curr = curr->next)
curr->print();
}
};
int main()
{
MyList ml;
T a(1),b(2),c(3);
ml.add_T(&a);
ml.add_T(&b);
ml.add_T(&c);
ml.print();
return 0;
}
答案 0 :(得分:2)
正如评论所说,您无条件取消引用head
,这会调用未定义的行为。由于要在头上添加节点,因此可以简单地执行以下操作:
T* add_T(T *x)
{
head = new T(x->getT(), head);
return head;
}
此外,更喜欢使用nullptr
,而不是NULL
。
此外,为所有数据成员提供默认值。例如在您的MyList
构造函数中,执行以下操作:
MyList()
{
head = nullptr;
}