C程序制作链表的第二个副本 [英] C program to make a second copy of a linked list
问题描述
我正在编写C代码,将链接列表的内容复制到另一个列表中.我想知道是否有更有效的方法.
I was writing a C code to copy the contents of a Linked List onto another list. I want to know if there is a more efficient way of doing this.
哪个更好?
struct node *copy(struct node *start1)
{
struct node *start2=NULL,*previous=NULL;
while(start1!=NULL)
{
struct node * temp = (struct node *) malloc (sizeof(struct node));
temp->info=start1->info;
temp->link=NULL;
if(start2==NULL)
{
start2=temp;
previous=temp;
}
else
{
previous->link=temp;
previous=temp;
}
start1=start1->link;
}
return start2;
}
OR
struct node *copy(struct node *start1)
{
if(start1==NULL) return;
struct node *temp=(struct node *) malloc(sizeof(struct node));
temp->info=start1->info;
temp->link=copy(start1->link);
return temp;
}
推荐答案
要将一个链表复制到另一个链表,您没有没有其他选择,但是要遍历一个并继续将值复制到第二个,总共O(n)
次.
您已经已经这样做了.除非存储的元素之间存在某种关联,否则没有办法做得更好.
For copying one linked list to another linked list, you have no other option but to iterate through one and keep copying the values to the second, in a total of O(n)
time.
You are already doing it. There is no way to do better unless there is some relation among the elements that are stored.
递归解决方案也许更好看,但实际上效率不高.
A recursive solution may be better to look at, but it will in fact be less efficient.
针对已更改的问题
迭代版本为更好的.
注意:LOC与效率没有直接关系.
这篇关于C程序制作链表的第二个副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!