-1

Here is the structure of the linked list:

struct Node
{
    char item;
    Node *next;
    Node(char Item, Node *Next = NULL);
};
Node *head;

I don't understand how to do this, I was told that this is the wrong way to do it

//copy constructor
Stack::Stack(const Stack& obj) {
    head = obj.head;
}

How do I make the correct copy constructor?

2 Answers2

1

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)) 
{
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • I'd swap the order in the `?:` to `return n ? new Node(n->item, copy_list(n->next)) : nullptr;` – Caleth Apr 25 '18 at 14:24
0

Regardless of the poor question, it's my helping day. So here you go. But if you don't come up with these solutions yourself, you're in a lot of trouble. This is the basics of c++.

struct Node {
    char item;
    Node *next;

    // Constructor
    Node(char Item, Node *Next = NULL) {};

    // Copy constructor 
    Node(Node const& other) {
        item = other.item;
        next = other.next;
    }
};
Kaveh Vahedipour
  • 3,412
  • 1
  • 14
  • 22