Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

As the comment says, you unconditionally dereferencing head, which invokes undefined behaviour. Since you are adding nodes to the head, you could simply do something like:

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

Also, prefer to use nullptr, instead of NULL.

Also, give all your data members default values. e.g. in your MyList constructor, do:

 MyList()
    {
        head = nullptr;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...