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.
Without going recursive, this is about the most compact you can get:
struct node *copy(struct node *org)
{
struct node *new=NULL,**tail = &new;
for( ;org; org = org->link) {
*tail = malloc (sizeof **tail );
(*tail)->info = org->info;
(*tail)->link = NULL;
tail = &(*tail)->link;
}
return new;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With