【发布时间】:2023-03-16 09:18:01
【问题描述】:
我正在编写一个 C 代码来将链接列表的内容复制到另一个列表中。我想知道是否有更有效的方法。
哪个更好?
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;
}
【问题讨论】:
-
您是在寻找运行时效率,还是寻求更紧凑/优雅的方式?
-
我猜是更优雅的做法。
-
比你应该递归的。
-
递归地这样做会非常优雅,但你必须小心,以免堆栈溢出。嘿嘿嘿嘿,今天双关语自己写的。说真的,你只能递归到目前为止,除非你使用的是尾递归语言,而 C 不是。
-
@user1161318 真正的男人使用
goto进行递归;-) 虽然,某些C 编译器实现(即带有扩展的GCC?)can optimize for TCO 在某些情况下......但它必须是TCO'able开始。
标签: c algorithm linked-list