复制带有链表的Ctor
Copy Ctor with Linked Lists
当使用链表时,我在实现深度复制方面遇到了很多困难。我确信问题是使用otherList.listData->给了我一个指向原始列表中数据的指针,而不是复制值。然而,我很困惑,否则我怎么能直接访问这些数据。我想你可以取消这些指针的围栏,但我一定有错误的语法。对于我从CourseList类中需要的数据,也没有get/set方法。
有人有什么想法吗???
头文件
class CourseList
{
private:
struct CourseNode
{
int CRN;
char letterGrade;
CourseNode *next;
};
int length;
CourseNode *listData;
public:
CourseList();
CourseList(const CourseList& otherList);
~CourseList();
};
CPP文件
CourseList::CourseList(const CourseList& otherList)
{
length = otherList.length;
for (int i = 0; i < length; i++)
{
CourseNode* temp = new CourseNode;
temp->CRN = otherList.listData->CRN;
temp->letterGrade = otherList.listData->letterGrade;
temp->next = otherList.listData->next;
listData = temp;
}
}
您的复制构造函数已损坏:它最终将最后一个元素分配给listData
,而不是第一个元素。这意味着您泄漏了列表中除最后一个元素之外的所有元素。此外,每次创建new CourseNode
时,都会将其next
指针分配给完全相同的东西——用于所有复制的元素!
不能只复制next
成员的值,因为该值将指向原始列表。
相反,你必须在迭代中设置它,比如这样的东西:
CourseNode *node = 0;
CourseNode *src = otherList.listData;
for (int i = 0; i < length; ++i)
{
CourseNode *next = new CourseNode();
if (node)
node->next = next; // already a previous node; update it
else
listData = next; // no previous node; set the very first one
next->previous = node; // optional in case your list is a double linked list
// now populate "node" with the original values (i.e. the actual copy operation)
node->CRN = src->CRN;
node->letterGrade = src->letterGrade;
// switch to the next source node
src = src->next;
}
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- C++,指针数组,指向双链表中的条目
- 链表中写入访问冲突的未知原因
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 打印所有链表的元素 (C++)
- 错误:需要类名(链表c++)
- 为什么C中的通用链表中存储的数据已损坏
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 链表c++插入,所有情况都已检查,但没有任何工作
- 链表,将列表复制到另一个列表
- 复制带有链表的Ctor
- 我的ctor使用链表和模板有什么问题