C++ 复制C+中未排序列表的构造函数+;

C++ 复制C+中未排序列表的构造函数+;,c++,data-structures,C++,Data Structures,我正在尝试为未排序的列表创建一个副本构造函数。下面是我的代码: UnsortedType::UnsortedType(const UnsortedType &s) { length = s.length; if (s.listData == NULL) { listData = NULL; return; } listData = new NodeType; NodeType *temp1 = listDat

我正在尝试为未排序的列表创建一个副本构造函数。下面是我的代码:

UnsortedType::UnsortedType(const UnsortedType &s)
{
    length = s.length;
    if (s.listData == NULL)
    {
        listData = NULL;
        return;
    }
    listData = new NodeType;
    NodeType *temp1 = listData, *temp2 = s.listData;
    while (temp2 != NULL)
    {
        temp1->info = temp2->info;
        temp2 = temp2->next;
        temp1->next = new NodeType;
        temp1 = temp1->next;
    }
    temp1 = NULL;
}

我不知道为什么,但最后一个节点没有设置为NULL。这在调用析构函数时会导致问题。析构函数删除节点,直到找到一个设置为NULL的节点。由于没有节点被设置为NULL,所以它会一直删除,直到遇到运行时错误。任何帮助都将不胜感激。

您将
temp1
设置为
NULL
;这只是一个局部变量。这是一件无用的事


我不清楚您的数据结构是如何工作的,但您可能想将最后一个
temp1->next
设置为
NULL
问题在于,如果语句中的temp2为NULL:

temp2 = temp2->next;
temp1 = NULL;
那么,您就没有必要为其分配内存了

temp1->next = new NodeType;
然后在语句末尾将temp1设置为NULL:

temp2 = temp2->next;
temp1 = NULL;
理想的代码应该是:

    while (1)
    {
        temp1->info = temp2->info;
        temp2 = temp2->next;
        if (temp2 != NULL) //Where temp2 is copyable
        {
             temp1->next = new NodeType;
             temp1 = temp1->next;
        }
        else
        {
             temp1->next = NULL;
             break;
        }
    }

为什么您的代码没有文档注释?而且我认为你的算法不对。除了结构,你没有复制任何东西吗?对不起,我不认为这对其他人来说会那么复杂,但你可能是对的。谢谢你解决它并解释问题。我没有意识到我不能将它从“newnodeType”更改为NULL。一个问题:如果我添加了delete temp;温度=零;这行得通吗?不行,不行。您应该能够将NULL指向上一个节点。删除当前节点并将其分配给NULL将不起作用。请研究单链表以获得更清晰的信息。您可以将其从“新节点类型”更改为空。然而,正如我的回答所解释的,这不仅是内存泄漏,而且毫无意义。