我写了这个函数:
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
。它在功能中有效,但一旦回到主程序就没有,为什么?
答案 0 :(得分:0)
似乎你想要head1和head2都指向同一个链表,你的代码的问题是你传递参数作为值调用,这就是为什么它没有反映你需要传递参数的函数通过Call By Pointer(参考)。 试试这种方式
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
}