我是一名C++初学者,尝试编写一个函数来创建C++中链接列表的深层副本。该函数调用自身,直到它位于源列表中的最后一个节点,然后复制该节点。但是,当我运行这个我得到一个分段错误或EXC_BAD_ACCESS错误。这是我到目前为止:C++深度复制链接列表
struct node {
int data;
node* next;
};
void copy_list(const node*& source_ptr, node*& dest_ptr)
{
if (dest_ptr != nullptr){
clear_list(dest_ptr);
}
if (source_ptr == nullptr) return; //we already cleared dest_ptr
if (source_ptr->next == nullptr) // this is the last node
{
dest_ptr = new node(); //initialize in memory
dest_ptr->data = source_ptr->data; //copy the last datum
dest_ptr->next = nullptr; //since this is the end
return;
}
const node* cursor = source_ptr->next; // this happens if source is not yet at the end
copy_list(cursor, dest_ptr->next);
}
我知道还有其他类似的问题,但他们没有帮助我。
dest_ptr = new node();
dest_ptr->data = source_ptr->data;
node* dest = dest_ptr->next;
const node* cursor = source_ptr->next;
while(cursor != nullptr)
{
dest = new() node;
dest-> data = cursor->data;
//dest->next = nullptr;
dest = dest->next;
cursor = cursor->next;
}
while循环不给错误,但复制是空白的(除了被外界所复制的第一个节点:我已经使用其他方法比递归例如while循环,看起来像也尝试while循环)。
任何帮助,非常感谢。谢谢!
你'while'环(应优于递归)的问题是该行'DEST = dest->接下来;'重新覆盖节点。 – 5gon12eder 2014-09-19 15:20:16
感谢您的评论,我可以看到您的观点。那么如何解决这个问题?我需要另一个变量吗?但我不知何故必须使用一个索引变量的while循环工作,对吧? – Kiochi 2014-09-19 15:49:21