Let's say I have a List class:
class List
{
private:
class Node{
public:
int data;
Node* next;
public:
virtual ~Node()
{
if (next != NULL)
delete next;
}
};
Node* head;
public:
virtual ~List()
{
if (head != NULL)
{
delete head;
}
}
public:
void AddNode(int data);
void DeleteNode(int data);
//....
};
Now I want to implement a function, which takes two List reference as arguments and return a new created List:
List SumTwoList(List& list_1, List& list_2)
{
//here I create a new List list_3 and add some elements to it based on list_1 and list_2(add operation use dynamic allocation).
//finally I want to return this list_3.
return list_3;
}
I am confusing here. How should I create this list_3
inside SumTwoList()
. If I just make it a local variable, when function returns, the destructor of list_3
will free all the nodes added to the list and destroy the whole list. However, if I do dynamic allocation to create this list_3
and return a pointer to it, it is the user's responsibility to delete this list after using.
I don't know how to choose from these two ideas and I'm pretty sure there are some much better methods to solve this problem. Thanks ahead for your advice. :-)