Creating a copy constructor for a linked list

前端 未结 5 1678
Happy的楠姐
Happy的楠姐 2020-12-09 09:03

This is homework

I\'m working on implementing a linked list class for my C++ class, and the copy constructor has be very confusing for me.

T

5条回答
  •  旧时难觅i
    2020-12-09 09:35

    You have to be careful with Step 1 and part of Step 2. Step 1 should allocate a new node and use that as the head. In Step 2, the part about next = v.next, unless your intention is to make a shallow copy, is incorrect.

    When you copy a container such as a linked list, you probably want a deep copy, so new nodes need to be created and only the data copied over. The next and prior pointers in the nodes of the new list should refer to new nodes you create specifically for that list and not the nodes from the original list. These new nodes would have copies of the corresponding data from the original list, so that the new list can be considered a by value, or deep copy.

    Here is a picture depicting the differences between shallow and deep copying:

    enter image description here

    Notice how in the Deep Copy portion of the diagram, none of the nodes point to nodes in the old list. For more information about the difference between shallow and deep copies, see the Wikipedia article on object copying.

提交回复
热议问题