Bagelstein
Bagelstein

Reputation: 202

Copy Ctor with Linked Lists

I am having a ton of trouble achieving a deep copy when using linked lists. I am pretty sure the problem is that using otherList.listData-> is giving me a pointer to the data in the original list rather than copying over the values. However, I am baffled as to how I can directly access that data otherwise. I was thinking you could just derefence those pointers but I must have the wrong syntax on that. There are also no get/set methods for the data I need from CourseList class.

Does anyone have any ideas???

Header File

class CourseList 
{
    private:
    struct CourseNode
    {
        int CRN;
        char letterGrade;
        CourseNode *next;
    };
    int length;
    CourseNode *listData;
public:
    CourseList(); 
    CourseList(const CourseList& otherList);
    ~CourseList(); 




};

CPP File

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

}

Upvotes: 0

Views: 66

Answers (2)

Mario
Mario

Reputation: 36527

You can't just copy the value of the next member, because that one will point to the original list.

Instead, you'll have to set that in your iteration, i.e. something like this:

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

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249424

Your copy constructor is broken: it ends up assigning the last element to listData instead of the first element. This means you leak all but the last element of the list. Also, each time you create a new CourseNode you assign its next pointer to the exact same thing--for all the copied elements!

Upvotes: 1

Related Questions