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

问题描述 投票:0回答:1

我想在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;
}
c++ linked-list singly-linked-list
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.