You are here:

C++/deep copy of a linked list

Advertisement


Question

hello

how can i perform a deep copy of a linked list?
i want to copy from linkedlistA to linkedlistB, but
when i delete linkedlistA, i want linkedlistB to still point to its own elements until i delete it separately

thanks

Answer
the deep copy certainly requires cloning the object. So when the listA is created with the values obtained using the object of the class use the same object and assign values to the list B.

This implies there are two copies of the same list list A and list B. So now , when you go ahead and delete list A , list B which is alike list A still exists and also it points to its elements.

The syntax may be like:

list<listclass>listA; /*here listclass is the class name and it    
list<listclass>listB; signifies the type of the list holds*/.
listclass a (i,j);/*invoking a 2 paramter constructor of class*/

Loop
listA.push_back(a.add()); /*adding elements to list */
end loop;
listclass b = a;/*invoking the copy constructor which does a deep copy */
Loop
listB.push_back(b.add());/*adding elements to listB*/
end loop;

Now though you delete listA which contains say 1,2,3 the contents of list B which are also 1,2,3 remain intact.

Does this answer your query.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Saikrishna

Expertise

I can answer questions in C (Basic and a little of advanced). I can't answer questions related to multi threading

Experience

2.6 years

Education/Credentials
I am a B-tech graduate majored in computer science.

©2016 About.com. All rights reserved.