Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c++ - Copy constructor for a pointer data linked list

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...