ListClass::ListClass(const ListClass& existingList)
: size(existingList.size)
{
if (existingList.head == NULL)
head = NULL; // original list is empty
else
{
// copy first node
head = new ListNode;
assert(head != NULL); // check allocation
head->item = existingList.head->item;
// copy rest of list
ListNode *newPtr = head; // new list pointer
// newPtr points to last node in new list
// origPtr points to nodes in original list
for (ListNode *origPtr = existingList.head->next;
origPtr != NULL;
origPtr = origPtr->next)
{
newPtr->next = new ListNode; // link new node to end of list
assert(newPtr->next != NULL);
newPtr = newPtr->next;
newPtr->item = origPtr->item; // copy the data
newPtr->next = NULL;
}
}
}
Basically you want to insert all of your copy constructor code into the assignment operator at line 12.
Once the assignment operator is working properly, you can rewrite your copy constructor as something like:
1 2 3 4 5
ListClass::ListClass(const ListClass& existingList)
: size(0), head(nullptr) // initialize to an empty list
{
*this = existingList; // use assignment operator to copy the data.
}
This is working below, although it's a little rough for me to fully comprehend, not that it's working, I can try some things out. We have a final on Wednesday:
SortListClass& SortListClass::operator=(const SortListClass& rhs)
{
// TODO
// Similar to Copy Constructor, except
// - Avoid self-assignments such as “X = X;”
// - Delete existing this-instance content before
// making this-instance a copy of the rhs instance
if (this != &rhs)
{
while (!isEmpty())
{
remove(1);
}
size = rhs.size;
}
if (rhs.head == NULL)
head = NULL; // ORIGINAL LIST IS EMPTY
else
{
// copy first node
this->head = new SortListNode;
assert(head != NULL); // check allocation
this->head->item = rhs.head->item;
// copy rest of list
SortListNode *newPtr = head; // new list pointer
// newPtr points to last node in new list
// origPtr points to nodes in original list
for (SortListNode *origPtr = rhs.head->next;
origPtr != NULL;
origPtr = origPtr->next)
{
newPtr->next = new SortListNode; // link new node to end of list
assert(newPtr->next != NULL);
newPtr = newPtr->next;
newPtr->item = origPtr->item; // copy the data
newPtr->next = NULL;
}
}
return *this;
};