复制带有链表的Ctor

Copy Ctor with Linked Lists

本文关键字:Ctor 链表 复制      更新时间:2023-10-16

当使用链表时,我在实现深度复制方面遇到了很多困难。我确信问题是使用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;
}