复制C++中未排序列表的构造函数
Copy Constructor for unsorted list in C++
我正试图为一个未排序的列表创建一个复制构造函数。以下是我的代码:
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
。
相关文章:
- 一对向量构造函数:初始值设定项列表与显式构造
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 构造函数/函数声明参数列表中的统一初始化
- 在初始化列表之外手动调用基类的构造函数
- 采用初始值设定项列表的构造函数
- 提供初始值设定项列表构造函数的有效方法
- C 标准中是否有任何计划来解决初始化器列表构造函数的不一致性
- 接受迭代器的初始值设定项列表构造函数
- STD :: MAP初始化列表构造函数
- 如何避免丢失自动生成的初始化列表构造函数
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- 初始化列表构造函数错误带有CRTP
- 启用默认初始值设定项列表构造函数
- 使用初始化列表构造函数时C++奇怪的行为
- 自定义列表类的初始值设定项列表构造函数
- 初始值设定项列表构造函数导致右值构造函数不明确
- 调用初始化列表构造函数的不同方式
- 为什么std::array不包含初始化列表构造函数
- C++ 为类模板提供初始值设定项列表构造函数
- 何时使用初始值设定项列表构造函数