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

Copy Constructor for unsorted list in C++

本文关键字:列表 构造函数 排序 C++ 复制      更新时间:2023-10-16

我正试图为一个未排序的列表创建一个复制构造函数。以下是我的代码:

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,因此它会一直删除,直到遇到运行时错误。如有任何帮助,我们将不胜感激。

问题是如果语句中的temp2为null

temp2 = temp2->next;

那么你就没有必要为分配内存

temp1->next = new NodeType;

然后在语句中将temp1设置为NULL

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

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

我不清楚您的数据结构是如何工作的,但可能您打算将最后一个temp1->next设置为NULL