gpt4 book ai didi

c++ - 链表复制构造函数

转载 作者:行者123 更新时间:2023-11-28 07:16:32 27 4
gpt4 key购买 nike

我最初必须使用 STL 创建自己的链表。现在,我要实现一个复制构造函数方法,但我很难理解它。几天后对此进行测试,所以我真的很想弄清楚。 (测试是闭卷的,所以真的需要)。该列表包含一个 EmployeeNode 指针 *head。 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;

关于c++ - 链表复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20153782/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com