Recursive CopyConstr. - Linked List

429 Views Asked by At

First of all, this is part of practice on Linked Lists and recursion. I'm trying to create a copy constructor that recursively deep copies a given LinkedList. I have coded the LinkedList methods already.

Problems I run into: it seems to be copying correctly during recursive calls, but fails to print afterwards. I believe either the list was not properly returned or a new list is being created every time. Definitely there is problem linking to the head, the list exists somewhere but head doesn't point to it?

Here's the necessary parts of the LinkedList.h file:

LinkedList::LinkedList(const LinkedList* list1)
{

if (list1 == NULL) { 
    std::cout << "End of Loop";
    return;
}

listLength = 0;
node newHead;
copy(list1->head,&newHead); // Start copy constructing 
}

void LinkedList::copy(const node * p1, node* p2)
{

if (p1 == NULL) {
    std::cout << "Copy Finished";
}

else { 
    node* p2 = new node;

    p2->artist = p1->artist;
    std::cout << p2->artist << "\t";
    p2->song = p1->song;
    std::cout << p2->song << "\n";

    listLength++;
     copy(p1->next,p2->next);

}

}

original list print

copied list - output correct while copying but print method fails?

ListLength of copied list is correct but no output??

0

There are 0 best solutions below