如何解决按值将链表传递给函数
编辑:我的结构是这样的:
struct node{
int key;
struct node* next;
}
typedef struct node* LIST;
我正在编写一个名为 print_list_iteratively
的函数,它接受一个单向链表并以相反的顺序迭代打印其元素。让我把我的 3 个函数放在下面,然后解释我的问题是什么?
LIST reverse_list(LIST L) {
LIST current = L,prev = NULL,subsequent = NULL;
while (current != NULL) {
// first we need to get the next element to not lose the link.
subsequent = current->next;
// now reverse the pointer
current->next = prev;
// we need to update our prev to create link between the currrent and next element.
// in short,we need to get the address of current node
prev = current;
// finally update the current
current = subsequent;
}
return (L = prev);
}
以上代码对列表L进行反转,返回列表L的新头。
void print_list(LIST L) {
while (L) {
printf("%d ",L->key);
L = L->next;
}
}
print_list
按元素的连接顺序打印列表中的元素。
我需要编写开头提到的 print_list_iteratively
函数。
void print_list_iteratively(LIST l) {
// first reverse the list,then call print_list. that's all.
printf("address of function parameter is %p\n",l);
l = reverse_list(l);
print_list(l);
}
我对这些功能没意见;它们按预期工作,但是当我试图理解函数如何将列表作为参数并返回它时,按值传递和按引用传递的概念让我感到困惑。让我简单地写一个 main 来测试这些,我们会看到事情是如何混合的。
int main(void) {
l = insert(l,5);
l = insert(l,10);
l = insert(l,15);
l = insert(l,45);
print_list(l);
print_list_iteratively(l);
print_list(l);
return 0;
}
当第一个 print_list
函数被调用时,它打印 5->10->15->45.
下一个 print_list_iteratively
在列表 l
上被调用,它依次调用 reverse_list
和 {{ 1}} 在函数体中。 print_list
中的 print_list
给出反向列表 print_list_iteratively
最终,主打印 45->15->10->5.
中的 print_list
我想知道为什么第二个 5.
刚刚打印了 print_list
?我已经将列表发送到 5
按值传递,而不是按引用传递,尽管如此,它在 print_list_iteratively
函数中更改了我的原始列表。有人能解释一下这个例子中的列表是如何传递给函数的,以及它们是如何从函数返回的吗?感谢您的回答。
解决方法
问题是你通过值传递头指针。这让您的程序可以修改您的链表,但头指针保持不变。
您应该通过引用或指向您的指针的指针将头指针传递给函数。 (node*& or node**
)
请记住,如果您通过指针传递它,则需要在需要时取消引用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。