获得C语言的递归级别?
我正在编写一个递归函数(用 C 语言),需要一种方法来知道递归是否完成。我想知道我是否可以在没有变量或标志的情况下做到这一点。以一个函数为例。
例如,如果递归下降了 3 级然后又回来了,有没有办法检查我是否处于第 1 级......而不使用标志?
级别 1 -> 2级-> 3级-> 2级-> 1 级(查看此处)
I was writing a recursive function (in C language) and needed a way to know if the recursion had finished. I wonder if I can do it withought variables or flags. With a function for example.
For instance, if the recursion went 3 levels down and then came back up, is there a way to check if I am at level 1....withought using flags?
lev 1 -> lev 2 -> lev 3 -> lev 2 -> lev 1 (check here)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要按照
int level
的方式向函数添加一个额外的参数。然后在递归调用自己时传递level+1
,并在初始调用时传递0
(或1
,如果您愿意)。You need to add an extra argument to your function, along the lines of
int level
. Then passlevel+1
when calling yourself recursively, and pass0
(or1
if you prefer) to the initial call.如果你想玩堆栈......
if you want to play with stack ...
如果您不关心可移植性,则可以手动展开调用堆栈。但我怀疑 R 的解决方案对于您的问题来说大大更好。
If you don't care about portability, you can unwind the call-stack manually. But I suspect R's solution is vastly better for your problem.
答案取决于实际问题。如果不存储某种标志,您就无法分辨(即以可移植的方式)。
但是,您的递归函数可能会碰巧以某种方式更改某些数据,以便它可以判断它之前是否已经进入某个递归深度。另一方面,这只是一种复杂的方式来表示您正在存储标志值。
The answer depends on the actual problem. Without storing some sort of flag, you can't tell (in a portable way, that is).
However, it's possible that your recursive function happens to alter some data in such a way that it can tell whether it has previously already entered into a certain recursion depth. On the other hand, this is just a complicated way of saying that you're storing a flag value.
也许您可以只检查调用堆栈,但这取决于您正在处理的实际级别或递归,否则,如果仅用于调试/理解目的,请使用 R.. 解决方案。
Maybe you can just check the call stack, but it will depend on the real level or recursion you are dealing with, else if it's for debug/understanding purpose only, go with R.. solution.