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?
For speed, there may in fact be a better way of doing it. As always, the only real way to tell is to benchmark it.
it may be faster to:
spend one iteration counting the length of the source list
int len = 0;
for (start2 = start1; start2 != NULL; start2 = start2->link)
++len;
allocate space for all required nodes in a single block
struct node *temp = malloc(len * sizeof(*temp));
and then spend a second iteration linking up your array of nodes
int i = 0;
for (start2 = start1; start2 != NULL; start2 = start2->link) {
temp[i].info = start2->info;
temp[i].link = &temp[i+1];
}
temp[len-1].link = NULL;
As I say, I'm not promising it will be faster (and it's certainly uglier), but it may be on some systems, with some compilers, under some conditions. Of course, it's a non-starter if the rest of your code assumes you can free individual nodes at will.
For elegance, recursion naturally wins.
The simple iterative approach is usually going to be a good compromise, though, between elegant but might explode unless you have a fancy TCO-ing compiler and the above, which is frankly a bit ugly and would benefit from an explanatory comment.