C 程序制作链表的第二个副本 [英] C program to make a second copy of a linked list

查看:21
本文介绍了C 程序制作链表的第二个副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 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;
}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆