开发者

Change recursive function to iterative

There is a recursive function f(). It is looking at cond and then either returning or executing f() then g(). Consider cond to be an external variable that can be set somewhere else, perhaps in a different thread.

  1. If the first five times cond is checked, cond == true, but the sixth time, cond == false, descri开发者_C百科be the code flow.

  2. Because this is recursive, the code could suffer from a stack overflow if cond == true for too long. Fill in the function iterative_f() so that the code flow is identical to the code flow in (1).

    //recursive
    
    void f()
    {
        if(cond == false)
            return;
        f();
        g();
    }
    
    //iterative  
    void iterative_f() {
    
    }
    


  1. Since the cond is false the 6th time, the function will in effect execute 5 times. The result is that function g will be executed 5 times.

  2. Now you can write the iterative function as follows:

    void iterative_f() 
    {
       while(cond)
       {
          g();
       } 
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜