【发布时间】:2019-09-24 21:14:30
【问题描述】:
我正在努力为双向链表实现复制构造函数。该程序可以编译,但我在使用复制构造函数中的“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();函数在我当前的实现中不起作用。
编辑:在调用 push_back 函数后,复制构造函数中的 while 循环卡住了。
编辑:“First”和“last”在 List 类声明中初始化,并且在构造函数中都设置为“nullptr”。
编辑:通过调试器运行后得知last->next = new_node;行中的push_back函数发生了非法内存访问(segmentation fault)
【问题讨论】:
标签: c++ linked-list copy-constructor