我写了这个函数:
void something(struct node* head1, struct node* head2)
{
statement 1 .......
statement 2 .......
so on.........
// Want to make list2 (head1) be the same as list1 (head1):
head2=head1
}
但这不会改变head2
。它在函数中执行,但返回主程序后就不再执行,为什么?
最佳答案
看来你希望 head1 和 head2 都应该指向同一个链表,你的代码的问题是你将参数作为按值调用传递,这就是为什么它没有反射(reflect)在你需要传递参数的函数之外通过指针调用(引用)。 试试这个方法
struct Node
{
int info;
Node *next;
}
main{
Node * head1,*head2;
// call like this
something(&head1,&head2);
}
something(Node **temphead1, Node **temphead2){
//here you can use
//(*temphead1)
//and
//(*temphead2)
//to perform operation
//for example you can display list item
while((*temphead1)!=null){
printf("%d",(*temphead1)->info);
(*temphead1)=(*temphead1)->next;
}
while((*temphead2)!=null){
printf("%d",(*temphead2)->info);
(*temphead2)=(*temphead2)->next;
}
// below line will do what you were looking for
(*temphead2)=(*temphead1);
// now you can check head1 =head2
}
关于c - 函数,链表。将一个链表复制到另一个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21938277/