[This page is auto-generated; please prefer to read the article’s PDF Form.]
We will use the parameter-less method recur2() to write a non-recursive equivalent of the recursive algorithm. As said earlier, we will maintain our own stack to simulate the recursive calls.
Method recur2() has no arguments and no local state to be stored on the stack for each call. We only need to store the equivalent of instruction-pointer (as happens for the call-stack) to indicate where to resume execution after a recursive call returns. There are two recursive calls in this method and hence only two possible resume-points (the very next statement to execute after a call returns). We will identify these resume-points by integers 1 and 2. A special value 0 of resume-point will be used to indicate a fresh call (not an actual resume); this will make our implementation simpler.
So, our stack-frame for each call is a very small one, consisting of only the resume-point. As recursive calls are made and return, these frames are pushed-on and popped-off the stack.
The global 4-tuple g can now be made local in the method; we will unwrap its members such that they also serve as the parameters of this method.
Following non-recursive equivalent of recur() is based on the above ideas:
Copyright © 2021 Nitin Verma. All rights reserved.