How can you emulate recursion with a stack?

前端 未结 4 801
半阙折子戏
半阙折子戏 2020-12-17 07:42

I\'ve heard that any recursive algorithm can always be expressed by using a stack. Recently, I\'ve been working on programs in an environment with a prohibitively small avai

4条回答
  •  失恋的感觉
    2020-12-17 07:53

    You can convert your code to use a stack like follows:

    stack.push(n)
    stack.push(i)
    while(stack.notEmpty)
        i = stack.pop()
        n = stack.pop()
        if (n <= i) {
            return n
        } else if (n % i = 0) {
            stack.push(n / i) 
            stack.push(i)
        } else {
            stack.push(n) 
            stack.push(i+1)
        }
    }
    

    Note: I didn't test this, so it may contain errors, but it gives you the idea.

提交回复
热议问题