I am a C++ beginner trying to write a function to create a deep copy of a linked list in C++. The function calls itself until it is at the last node in the source list, then copies that node. However when I run this I get a segmentation fault or EXC_BAD_ACCESS error. Here is what I have so far:
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);
}
I know there are other questions similar to this, but they haven't helped me. I have also tried using other methods than recursion for example a while loop that looks something like:
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;
}
The while loop doesn't give errors but the copy is blank (except for the first node which is copied outside the while loop).
Any help is greatly appreciated. Thanks!