Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program to make a second copy of a linked list

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;
}
like image 289
user Avatar asked Nov 29 '12 19:11

user


2 Answers

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.

like image 172
axiom Avatar answered Oct 02 '22 12:10

axiom


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;
}
like image 38
wildplasser Avatar answered Oct 02 '22 11:10

wildplasser