I want to implement single linked list in C++. I have a segmentation fault problem. I think it's the add function issue. Can anybody check and say how can I imporove this?
#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 << "
";
}
};
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;
}
EDIT:
Still not what I wanted, because I see the 0 from head node.
#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 << "
";
}
};
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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…