c - 函数,链表。将一个链表复制到另一个链表

标签 c linked-list

我写了这个函数:

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/

相关文章:

c++ - C 中的 limit.h 未确认值

c - 函数的存在会中断 HTTP 请求

c - 替换 For 循环的宏

Java 集合 addAll 复杂性

c - 变量 'c' 已设置但未使用 [-Wunused-but-set-variable]

c - 使用链表进行两个多项式相乘的程序

c - freopen 或 freopen_s,它们到底在做什么?

c - 安思 C : Long Double Variable Printing Out to a Value of 0. 000000

java - 使用归并排序对双向链表进行排序

C QueueLinkedList 字符串变量不起作用