递归转手动管理栈的非递归

# 递归转非递归
#自己管理栈,关键在于模拟函数调用的过程

# 栈结构
class Lstack():
    def __init__(self,top=-1,full=20):
        self._top = top
        self._stack=[]
        self.full = full
    def is__full(self):
        return self.full == self._top+1
    def is_empty(self):
        return self._top == -1
    def push(self,x):
        if self.full == self._top+1:
            print("堆栈已满")
        else:
            self._stack.append(x)
            self._top += 1
    def pop(self):
        if self._top == -1:
            print("堆栈为空,不可弹出")
        else:
            top =self._top
            self._top -= 1
            return self._stack.pop(top)

        
#阶乘递归函数
def fact(n):
    if n==0:
        return 1
    else:
        return n*fact(n-1)

def fact1(n):
    res=1 #保留的参数
    st =Lstack()
    while n>0:
        st.push(n)
        n -= 1
    while not st.is_empty():
        res *=st.pop()
    return res

猜你喜欢

转载自blog.csdn.net/Tommy1295/article/details/80949709