gpt4 book ai didi

c++ - 为双向链表实现复制构造函数时遇到问题

转载 作者:搜寻专家 更新时间:2023-10-31 01:24:33 24 4
gpt4 key购买 nike

我正在努力为双向链表实现复制构造函数。该程序可以编译,但我在使用复制构造函数中的“push_back”函数将新创建的节点添加到列表中时遇到了问题。下面是有问题的复制构造函数和 push_back 函数。

List::List(const List& rhs) // Copy constructor
{
//this pointer is for the list that is being copied from
Node* rhsNodePtr;

//setting the new pointer to the first node of the old list
rhsNodePtr = rhs.first;

//looping until the end of the list
while(rhsNodePtr != nullptr){

//declaring new node to copy data into
Node* newNode = new Node("");

//copying node data from original list into new node
newNode->data = rhsNodePtr->data;

//adding new copied node to a new list
push_back(newNode->data);

//advancing the old list pointer location for the loop
rhsNodePtr = rhsNodePtr->next;
}
}

void List::push_back(string element)
{
Node* new_node = new Node(element);
if (last == nullptr) // List is empty
{
first = new_node;
last = new_node;
}
else
{
new_node->previous = last;
last->next = new_node;
last = new_node;
}
}

如果我遗漏了任何相关细节,我深表歉意。请注意,我不仅在寻找解决方案或更正,而且还在寻找 push_back(); 原因的解释。函数在我当前的实现中不起作用。

编辑:复制构造函数中的 while 循环在调用 push_back 函数后卡住。

编辑:“First”和“last”在 List 类声明中初始化,并在构造函数中都设置为“nullptr”。

编辑:通过调试器运行后,我了解到 last->next = new_node; 行中的 push_back 函数中发生了非法内存访问(段错误)

最佳答案

您没有在复制构造函数中初始化 last。所以 push_back 被调用时带有垃圾。

顺便说一句,我看不到需要 newNode 并且您没有释放它。您可以直接push_back(rhsNodePtr->data);

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

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