Reputation: 1075
I'm trying to make a deep copy for my simple linked list that I've made. I'm trying to get the basics of it and any help would be appreciated. I just want to take the first value in the old list and deep copy it to the new list.
#include<iostream>
using namespace std;
struct listrec
{
char value;
struct listrec *next;
};
void deepcopy(listrec *old_linked_list, listrec *new_linked_list)
{
while(old_linked_list != NULL)
{
new_linked_list->value = old_linked_list->value;
new_linked_list->next = old_linked_list->next;
old_linked_list = old_linked_list->next;
new_linked_list = new_linked_list->next;
}
}
int main()
{
listrec x1,x2,x3;
listrec *head_old, *head_new=NULL;
x1.value = 'a';
x1.next = &x2;
x2.value = 'c';
x2.next = &x3;
x3.value = 'w';
x3.next = NULL;
head_old = &x1;
head_new = head_old;
deepcopy(head_old, head_new);
//print old list
cout<<"Old List: "<<endl;
while(head_old != NULL)
{
cout<<head_old->value<<endl;
head_old= head_old->next;
}
cout<<endl;
//print copied list
cout<<"Copied list: "<<endl;
while(head_new != NULL)
{
cout<<head_new->value<<endl;
head_new= head_new->next;
}
system("pause");
return 0;
}
The program works and it makes a copy but I just want to make sure its a deep copy and not a shallow copy. What do you guys think?
Upvotes: 1
Views: 978
Reputation: 9032
You are passing head_new
which is NULL to deepcopy
. Then you try to deference (access) it. This gives you segmentation fault (error), since you cannot deference a NULL pointer. (You cannot access nothing, because your pointer points to nothing.)
To correct your code must allocate memory for head_new
in main
and for each next node in in deepcopy
. Also you should move on your new_linked_list
, as you assign all the time to the same node.
Upvotes: 1