Copy constructor for a pointer data linked list

浪子不回头ぞ 提交于 2019-12-14 00:12:48

问题


Can you help me to write a copy constructor for this List, note that the Data is stored indirectly.

     class List {
         private:
         struct Node {
            Data *data;
            Node *next;
         };
         Node *head;
    };

You can assume you have a copy constructor of Data class.

Thank you.


回答1:


Your class definition needs to add the function signature:

List(const List& list);

The parameter is the list you are copying from.

You also need to implement this function.

  List::List(const List& list)
  {
    //Iterate through the list parameter's nodes, and recreate the list
    //exactly as it is in the list you passed in.
  }

Note that you probably don't want to do this:

  List::List(const List& list)
  {
    head = list.head;
  }

because instead of being a copy of the list, it's actually a second reference to the same list.

You can call this function like this:

List thisIsAPremadeList;
List copyOfList(thisIsAPremadeList);

And now copyOfList contains a deep copy of everything that thisIsAPremadeList has.



来源:https://stackoverflow.com/questions/42523112/copy-constructor-for-a-pointer-data-linked-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!