Saturday, 7 September 2013

C++ constructor that deep copies a linked list

C++ constructor that deep copies a linked list

I am a noob to C++ and programming in general and am trying to make a
constructor which will duplicate a linked list. The idea is that I can use
Individual* copyOfList = new Individual(originalList->getFirstBit());
to make a deep copy of the original list.
But my cose below seems not to be doing a deep copy. When I edit the
copyOfList the originalList is efected aswell. And I don't understand
linked lists enough to make it deep copy. Can someone help me please.
Individual::Individual(BinaryNode* copyHead)
{
head = copyHead;
NodePtr last = NULL;
NodePtr temp = NULL;
curr = head;
while (curr != NULL)
{
temp = new BinaryNode(curr->data, NULL);
if(last != NULL)
{
last->next = temp;
}
last = temp;
if (head == NULL)
{
head = temp;
}
curr = curr->next;
}
}

No comments:

Post a Comment