I'm trying to write a function to copy the contents of one linked list into a new linked list (no reference to the first LL). I've so far got this:
void List::copy(const List& otherList)
{
assert(head == nullptr);
if (otherList.head != nullptr)
{
head = new Node;
assert(head != nullptr);
head->item = otherList.head->item;
Node* ptr1 = head;
for (Node* ptr2 = otherList.head->next; ptr2 != nullptr; ptr2=ptr2->next)
{
ptr1->next = new Node;
assert(ptr1->next != nullptr);
(ptr1->next)->item = ptr2->item;
(ptr1->next)->next = ptr2-> next;
}
}
}
However when I run the code on a small linked list, it simply copys the first and last nodes - for some reason it misses out the middle part. I've spent a while researching other peoples solutions and trying to figure out whats going wrong with mine, however i've hit a brick wall!
Could someone possibly point out where i'm going wrong?
Kind regards
Craig
ptr1(in other words, it always points tohead). Thus you get the head and tail into your new list.