Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Copy constructor for very simple singly linked list?

I am having quite a bit of difficulty understanding how to implement a copy constructor for a singly linked list. Heres is the code I have for the implementation:

-------------------------------------------------------

struct node {

string value;

node * next;

};

class strSet {

private:

node * first;

public:

...

strSet (const strSet& copy);

...

};

------------------------------------------------------

I am having difficulty implementing this copy constructor. Can anyone shed some light? I'm not sure what to put in the body.

strSet (const strSet& copy) {

if( copy->first == NULL) first = NULL;

.....

Update:

The other public member functions don't relate to the copy constructor. I'm suppose to do a deep copy manually.

2 Answers

Relevance
  • 1 decade ago
    Favorite Answer

    You can go after this tut for your problem :

    http://www.smccd.net/accounts/hasson/C++2Notes/Lin...

  • 1 decade ago

    First, let's do this one step at a time:

    strSet(const strSet ©) {

    ...first = copy.first; // Copy the pointer to their node, for a starter

    ...struct node **next = &first; // Show that we're working on the First pointer

    ...while (**next) { // Proceed while we need to clone nodes

    ......struct node *newNode = malloc(sizeof(struct node); // Allocate a node

    ......*newNode = **next; // Fill it

    ......*next = newNode; // Have the pointer we're working on point at the new storage

    ......next = &newNode->next; // Advance to work on the next pointer

    ...}

    }

    This collapses to:

    strSet(const strSet ©) {

    ...first = copy.first;

    ...for (struct node **next=&first; **next; next=&newNode->next) {

    ......struct node *newNode = malloc(sizeof(struct node);

    ......*newNode = **next;

    ......*next = newNode;

    ...}

    }

Still have questions? Get your answers by asking now.