GermaineJason
GermaineJason

Reputation: 589

Linked list copy constructor

I originally had to create my own linked list with using the STL. Now, I am to implement a copy constructor method and I am having real difficulty understanding it. Have a test on this in a few days so I would really like to get it clear. (Test is closed book so need to really). The List contains a EmployeeNode pointer *head. The EmployeeNode contains an Employee and a pointer to the next EmployeeNode. The Employee class contains a name and salary.

The method seems to get caught in the for loop when trying to copy the 3rd node over. I think this is because I overwrite the newNode but I do not know how to solve this.

ListOfEmployee::ListOfEmployee(const ListOfEmployee &obj)
{
    head = NULL;

    if(obj.head != NULL)
    {
        EmployeeNode *newNode  = new EmployeeNode("", 0);
        EmployeeNode *tempPtr;
        EmployeeNode *newPtr;

        //using the temp pointer to scroll through the list until it reaches the end
        for(tempPtr = obj.head; tempPtr->next !=NULL; tempPtr = tempPtr->next)
        {
            if(head == NULL)
            {
                cout<<"Attempts to initialize the head"<<endl;

                head = newNode; //assinging the new node to the head
                newNode->emp.name = tempPtr->emp.name;
                newNode->emp.salary = tempPtr->emp.salary;

                cout<<"Initializes the head"<<endl;
            }
            else
            {
                cout<<"Attempts to add a new node"<<endl;

                //using the temp pointer to scroll through the list until it reaches the end
                for(newPtr = head; newPtr->next !=NULL; newPtr = newPtr->next)
                {
                    cout<<"Looping through the list"<<endl;
                }

                //assiging the last place to the new node
                newPtr->next = newNode;
                newNode->emp.name = tempPtr->emp.name;
                newNode->emp.salary = tempPtr->emp.salary;

                cout<<"Adds a new node"<<endl;
            }
        }
    }
}

Upvotes: 0

Views: 4141

Answers (1)

benipalj
benipalj

Reputation: 704

In your code where you are adding newNode in newPtr->next = newNode; you are basically using previously allocated node. You should create a new node using new. Something like:

newPtr->next = new EmployeeNode("", 0);
newNode = newPtr->next;
newNode->emp.name = tempPtr->emp.name;
newNode->emp.salary = tempPtr->emp.salary;

Also you should set newNode->next = NULL; in your code.

Upvotes: 1

Related Questions