You need to create a new list with the same structure and the same items, but not the same nodes, as obj.head
.
This is very convenient to do recursively:
Node* copy_list(const Node* original)
{
if (original == nullptr)
{
return nullptr;
}
Node* tail_copy = copy_list(original->next);
return new Node(original->item, tail_copy);
}
or even
Node* copy_list(const Node* n)
{
return n == nullptr ? nullptr : new Node(n->item, copy_list(n->next));
}
or you can do it iteratively, which gets a bit more cumbersome:
Node* copy_list(const Node* n)
{
Node* head = nullptr;
Node* current = nullptr;
while (n != nullptr)
{
Node* new_node = new Node(n->item);
if (head == nullptr)
{
head = new_node;
}
else
{
current->next = new_node;
}
current = new_node;
n = n->next;
}
return head;
}
and then
Stack::Stack(const Stack& obj)
: head(copy_list(obj.head))
{
}