【发布时间】:2012-01-10 00:49:58
【问题描述】:
我正在尝试为我制作的简单链接列表制作一个深层副本。我正在尝试了解它的基础知识,任何帮助将不胜感激。我只想获取旧列表中的第一个值并将其深度复制到新列表中。
#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;
}
该程序可以运行并且它会创建一个副本,但我只是想确保它是一个深层副本而不是浅层副本。大家觉得呢?
【问题讨论】:
标签: visual-c++ linked-list deep-copy