0
我原本不得不使用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;
}
}
}
}
谢谢。现在看起来很明显! – GermaineJason
另外,newNode-> next在EmployeeNode构造函数中初始化为NULL。 – GermaineJason