开发者

Drawing the call stack in a recursive method

I want to draw the call stack for any recursive method, so I've created a schema like this,

recursiveMethod(){
  //Break recursion condition
  if(){
     // Add  value here to the return values' list- No drawing
     return
   }
  else{
    //Draw stack with the value which will be pushed to the stack here
    variable <- recursiveMethod()
   //Clear the drawing which represents the poped value from the stack here
   return variable
}}

Applying the schema will look something like this,

Drawing the call stack in a recursive method

Notes:

  1. This schema can draw recursive methods with n recursive call by making the recursive calls in a separate return statements.
  2. returnValues list, is a list which save all the return values, just for viewing issues.
  3. Draw stack means, simply Draw a simp开发者_如何学Cle cell "rectangle" + Drawing the pushed String.

What do you think of this? any suggestions are extremely welcomed.


I'm not sure if I understand your question correctly, but will take a stab at it, let me know if this is incorrect.

What I gather is that you want some way to keep track of you stack within a recursive function. One way you can do this is to have a Stack data structure, and a function that draws the data structure,how you wish to draw it is up to you, for now maybe just draw the stack as something like [---] with the '-' being the recursive depth.

Here is an approximate C++ like example:

So we have:

Stack recursiveFunctionTrackingStack; //Stack of something, maybe just '-'

void DrawStack(const Stack& aStack);

and another type something like:

struct StackUpdater
{
    StackUpdater(){ recursiveFunctionTrackingStack.push('-'); }
    StackUpdater(const string& somevalue)
    { 
        recursiveFunctionTrackingStack.push(somevalue); 
    }
    ~StackUpdater(){ recursiveFunctionTrackingStack.pop(); }
}

so the 'StackUpdater' pushes something on the Stack data structure when an object of it is created, and pops it off when it is destructed.

Now within the recursive function we can do (using your code snippet):

recursiveMethod(){
  if(){ return }
  else{
    {
        StackUpdater su(pushedInValue); //Value pushed
        variable <- recursiveMethod();
        DrawStack(recursiveFunctionTrackingStack);
    } //Value popped on destruct.
    DrawStack(recursiveFunctionTrackingStack); 
   return variable
}}

Maybe what you want is something along those line. If not, then please clarify you question.

Hope this helps anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜