链表复制构造函数

Linked list copy constructor

本文关键字:构造函数 复制 链表      更新时间:2023-10-16

我最初不得不使用STL创建自己的链表。现在,我要实现一个复制构造函数方法,我很难理解它。几天后再做一个测试,所以我真的很想弄清楚它。(测试是一本封闭的书,所以真的需要)。该列表包含EmployeeNode指针*头。EmployeeNode包含Employee和指向下一个EmployeeNode的指针。Employee类包含名称和薪资。

当试图复制第三个节点时,该方法似乎陷入了for循环。我想这是因为我覆盖了newNode,但我不知道如何解决这个问题。

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

newPtr->next = newNode;中添加newNode的代码中,基本上使用的是以前分配的节点。您应该使用new创建一个新节点。类似于:

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

此外,您应该在代码中设置newNode->next = NULL;