[英]How can I insert a node in a singly linked list using recursion given: 1. a pointer to the head node 2. the index to insert the new node
[英]How can I edit a pointer to a list node from a function in a recursion?
直到现在,我一直在编写一个相当复杂的程序。 无论如何,我应该编写一个操作结构列表的函数。 我试图让这个问题尽可能简单,所以我写下了一段非常简单的代码供参考。
事情是这样的:首先我从另一个函数调用testf
,为它提供有效current
以及值为0的i
。这意味着testf在开始访问其余代码之前会调用自己大约100次。 这是所有生成的testf
实例开始得到解决的时候。
void testf(listnode *current, int *i) {
wordwagon *current2;
current2 = current;
if (*i < 100) {
*i = *i + 1;
current2 = current2->next;
testf(current2, i);
}
current = current->next;
return;
}
如果,假设我有足够的连接列表节点,那么current = current->next;
“最后”testf函数访问和编辑调用者的current2
值(这是该函数的current
)的正确方法,还是我可怕的错误? 如果我是,从被调用函数内部更改调用函数的变量的方法是什么,并确保它们不会在被调用函数返回后立即消失? 我发现很难掌握指针的工作原理。
我很可能遗漏了重要信息,或者我没有清楚地问我的问题。 如果是这种情况请通知我,以便我可以根据您的需要进行编辑。
提前致谢。
您可以将指针传递给函数中的指针,并将其解析以获取listnode指针,这是代码在此之后的样子(未经过编译测试):
void testf(listnode **current, int *i) { // accept pointer to listnode pointer
wordwagon *current2;
current2 = *current; // retreive pointer value by dereferece
if (*i < 100) {
*i = *i + 1;
current2 = current2->next;
testf(¤t2, i); // recursively call by reference to the pointer
}
*current = (*current)->next; /* change the current pointer next pointer, CORRECTED as suggested by Azure */
return;
}
这是学习指针的非常好的文章列表:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.