单链表,C++分段错误,添加到列表,打印



我想在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节点看到了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;
}

正如注释所说,您无条件地取消引用head,这会调用未定义的行为。由于您正在向头部添加节点,因此可以简单地执行以下操作:

T* add_T(T *x)
{
head = new T(x->getT(), head);
return head;
}

此外,更喜欢使用nullptr,而不是NULL

此外,为所有数据成员指定默认值。例如,在MyList构造函数中,执行:

MyList()
{
head = nullptr;
}

相关内容

  • 没有找到相关文章

最新更新