2014-10-22 66 views
0

使用链接列表时,我遇到了很多麻烦实现深层复制的问题。我很确定问题是使用otherList.listData->给我一个指向原始列表中的数据的指针,而不是复制这些值。但是,我对如何直接访问数据感到困惑。我以为你可以放弃这些指针,但我必须有错误的语法。对于CourseList类所需的数据,也没有get/set方法。使用链接列表复制Ctor

有没有人有任何想法?

头文件

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

} 
+0

敢肯定你正在试图做的[这样的事情(http://ideone.com/ JcFPfR)。 – WhozCraig 2014-10-22 11:49:44

回答

1

你的拷贝构造函数被打破:它结束了最后一个元素分配给listData的第一要素来代替。这意味着你泄漏了除列表的最后一个元素外的所有元素。此外,每次创建new CourseNode时,都会将其指定的next指针指向完全​​相同的内容 - 对于所有复制的元素!

+0

虽然暂时忽略这一部分,但我可以在之后解决这个问题。关于我原来的问题的任何想法? – Bagelstein 2014-10-22 08:30:33

+0

我不明白,我告诉你,你的代码被严重破坏的具体地方,你想“忽略”,并专注于......什么? – 2014-10-22 09:37:25

+0

我认为我的问题是如何分配值,而不是担心其余的问题,但看起来我的任务很好,而且我的错误确实与更新指针有关。其他人试图帮助解决这个问题,但是我现在用他们的例子工作了一个多小时,并且完全没有运气。你有什么机会提供更多的指导? – Bagelstein 2014-10-22 09:55:25

0

您不能复制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; 
} 
+0

原始值的人口是我遇到的困难。是的,我在节点间移动的过程中出现了一个错误,由于我遇到了麻烦,我还没有到达那个部分。有任何想法吗? – Bagelstein 2014-10-22 08:34:30

+0

@ user3889565我已经用该部分更新了我的代码片段。请尽量了解发生了什么,然后再复制并使用它。 :) – Mario 2014-10-22 08:37:58

+0

根据这个我正确使用otherList.listData-> CRN等。不幸的是,即使我做出调整,以便节点更新正确,仍然会得到相同的访问冲突错误。我将不得不继续调整它。 – Bagelstein 2014-10-22 08:48:14