链表的深度拷贝c++



我正试图为我所做的简单链表做一个深拷贝。我正试图得到它的基础知识,任何帮助将不胜感激。我只想取旧列表中的第一个值并将其深度复制到新列表中。

#include<iostream>
using namespace std;
struct listrec
{
char        value;
struct listrec    *next;
};

void deepcopy(listrec *old_linked_list,  listrec *new_linked_list)
{
while(old_linked_list != NULL)
{
    new_linked_list->value = old_linked_list->value;
    new_linked_list->next = old_linked_list->next;
    old_linked_list = old_linked_list->next;
    new_linked_list = new_linked_list->next;
}
}

int main()
{
listrec x1,x2,x3;
listrec *head_old, *head_new=NULL;
x1.value = 'a';
x1.next = &x2;
x2.value = 'c';
x2.next = &x3;
x3.value = 'w';
x3.next = NULL;
head_old = &x1;
head_new = head_old;
deepcopy(head_old, head_new);
//print old list
cout<<"Old List: "<<endl;
while(head_old != NULL)
{
    cout<<head_old->value<<endl;
    head_old= head_old->next;
}
cout<<endl;
//print copied list
cout<<"Copied list: "<<endl;
while(head_new != NULL)
{
    cout<<head_new->value<<endl;
    head_new= head_new->next;
}

system("pause");
return 0;
}

程序工作了,它做了一个拷贝,但我只是想确保它是一个深拷贝,而不是浅拷贝。你们怎么看?

您正在传递NULL的head_newdeepcopy。然后你试着去遵从(接近)它。这会给你分段错误(错误),因为你不能遵从NULL指针。(你不能访问什么,因为你的指针指向什么。)

要纠正您的代码必须为main中的head_newdeepcopy中的每个下一个节点分配内存。此外,你应该移动你的new_linked_list,因为你一直分配到相同的节点。

最新更新