复制指针数据链表的构造函数

时间:2017-03-01 04:19:15

标签: c++ linked-list

你能帮我写一下这个List的拷贝构造函数吗,注意数据是间接存储的。

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

您可以假设您拥有Data类的复制构造函数。

谢谢。

1 个答案:

答案 0 :(得分:1)

您的类定义需要添加函数签名:

List(const List& list);

参数是您要复制的列表。

您还需要实现此功能。

  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.
  }

请注意,您可能 想要这样做:

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

因为它不是列表的副本,而是实际上对相同列表的第二次引用。

您可以像这样调用此函数:

List thisIsAPremadeList;
List copyOfList(thisIsAPremadeList);

现在copyOfList包含thisIsAPremadeList所拥有的所有内容的深层副本。

相关问题