Just by glancing at it, why is the constuctor accepting an argument of const object? Constructor actually changes the values, you are placing value of copyPtr to the node and changing the next pointer to null.
I changed it to this and the program is not crashing anymore but it is still not giving me the correct output. The output is giving me 15 20 25 15 and it should be 15 20 25 15 20 25.
This is my current copy constructor. It copies the nodes and the program displays them but the program does not finish so there is still a bug somewhere and I cannot find it. I know that it's not calling the second destructor.
1 2 3 4 5 6 7 8 9 10 11 12 13
LinkedList::LinkedList(const LinkedList& listObj)
{
ListNode* newNode = nullptr; // Create new node
ListNode* copyPtr = nullptr; // Point to original object
copyPtr = listObj.head;
while(copyPtr->next != nullptr)
{
newNode->next = new ListNode;
newNode->value = copyPtr->value;
}
}
calm down, analyse it, write some pseudocode, make sure it is correct, then code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
LinkedList::LinkedList(const LinkedList& listObj)
{
ListNode* nodePtr = nullptr;
ListNode* newNode = new ListNode;
ListNode* copyPtr = listObj.head;
newNode->value = copyPtr->value; //if listObj is empty, you are dereferencing a null pointer
newNode->next = nullptr;
if(!head) //head is unititialized
head = listObj.head; //shallow copy
while(copyPtr->next != nullptr) //if listObj is empty, you are dereferencing a null pointer
{
appendNode(copyPtr->value); //don't know what this does
copyPtr = copyPtr->next;
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
LinkedList::LinkedList(const LinkedList& listObj)
{
ListNode* newNode = nullptr;
ListNode* copyPtr = listObj.head;
newNode = new ListNode;
head = newNode;
newNode->value = copyPtr->value; //same problem with empty list
copyPtr = copyPtr->next;
while(copyPtr->next != nullptr) //now problem with list with just one element
{
newNode = new ListNode; //leaking memory
newNode->value = copyPtr->value;
copyPtr = copyPtr->next;
//you never link your nodes
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14
LinkedList::LinkedList(const LinkedList& listObj)
{
ListNode* newNode = nullptr; // Create new node /*your comment does not match with the code*/
ListNode* copyPtr = nullptr; // Point to original object /*same here, ¿original object, what's that?*/
copyPtr = listObj.head;
while(copyPtr->next != nullptr) //same problem with empty list
{
newNode->next = new ListNode; //newNode is null in the first iteration, UB
newNode->value = copyPtr->value;
}
//in the last node `next' holds garbage
}