单链表,C ++分段错误,添加到列表,打印 [英] Single Linked List, C++ segmentation fault, add to list, print

查看:44
本文介绍了单链表,C ++分段错误,添加到列表,打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中实现单个链表.我有一个细分错误问题.我认为这是添加功能的问题.有人可以检查并说出我该如何改善吗?

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 << "\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.

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 << "\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,这会调用未定义的行为.由于要在头上添加节点,因此可以简单地执行以下操作:

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;
    }

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

Also, prefer to use nullptr, instead of NULL.

此外,为所有数据成员提供默认值.例如在您的 MyList 构造函数中,执行以下操作:

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

 MyList()
    {
        head = nullptr;
    }

这篇关于单链表,C ++分段错误,添加到列表,打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆