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.
Which is better?
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;
}
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.
Edit: For the changed question
The Iterative version is better.
Note : LOC has no direct relation with efficiency.