I am writing a copy function for linked lists (called OLList) which contain a structure called Node. Node has an integer (renamed ListItem) called item, and a pointer of type Node called Next.
I am getting strange results. Any ideas as to what is wrong?
Here a simple class for the linked list without getters/setters
struct Node {
ListItem item;
Node *next;
};
class OLList {
private:
Node *headM;
};
here is the function
void OLList::copy(const OLList& source)
{
if(source.headM==0)
return;
Node *after=source.headM->next;
Node *temp=new Node;
int *data_1=new ListItem;
if(temp==NULL || data_1==NULL)
exit(1);
data_1=&source.headM->item;
temp->item=*data_1;
Node *ret=temp;
while(after!=0){
temp=temp->next;
temp=new Node;
int *data=new ListItem;
if(temp==NULL || data==NULL)
exit(1);
data=&after->item;
temp->item=*data;
after=after->next;
}
temp->next=0;
headM=ret;
delete temp;
}
I have a control link list called the_list:
[ 99, 110, 120, 220, 330, 440, 550 ]
and I copy the linked list TWICE in two different ways. I should mention that this function is called by the assignment operator.
OLList other_list;
other_list = the_list;
OLList third_list = the_list;
The assignment operator (cannot be changed, b/c it was assigned to me):
OLList& OLList::operator =(const OLList& rhs)
{
if (this != &rhs) {
destroy(); //this is to prevent self copy
copy(rhs); //function is called here
}
return *this;
}
I get the following outputs respectively:
testing for copying lists ...
other_list as a copy of the_list: expected to be [ 99, 110, 120, 220, 330, 440, 550 ]
[ 99 ]
third_list as a copy of the_list: expected to be: [ 99, 110, 120, 220, 330, 440, 550 ]
[ 99, -2144292712, -2144292728, -2144292744, -2144292760, 0 ]
so the first one copies just the first element, and the second one copies who knows what... I am still new to programming so please ELI5! Thank you.
if(source.headM==0) return;after copying from an empty list I would expect that both are empty. Anyhow, please provide a minimal reproducible examplesourceis a reference, it cannot point to NULL, and again: If i copy from a list that has nothing inside, I would expect that afterwards both lists contain the samecopyis never called.