fib函数递归实现:

        long Fib(long n) 
{
if (n <= 1)
{
return n;
}
else
{
var t1 = Fib(n - 1);
var t2 = Fib(n - 2);

return t1+ t2;
}

}

fib函数改为迭代:

    class Class1
{
class Node
{
public Node(long n, int pos)
{
this.n = n;
this.retStatus = pos;
}

public long n; //参数
public int retStatus;
//0,表示temp中没有保存值
//1, 表示temp中保存了栈顶记录的t1值。
//2,表示temp中保存了栈顶记录的t2值。

public long ret; //返回值
public long t1; //存第一次调用Fib的返回值
public long t2; //存第二次调用Fib的返回值
}

long Fib(int n)
{
long temp = 0;

var s = new Stack<Node>();
s.Push(new Node(n, 0));

while (s.Count > 0)
{
Node top = s.Peek();

switch (top.retStatus)
{
case 0:
if (n <= 1)
{
top.ret = n;
temp = top.ret;
s.Pop();
}
else
{
top.retStatus = 1;
s.Push(new Node(n - 1, 0));
}
break;
case 1:
top.t1 = temp;

top.retStatus = 2;
s.Push(new Node(n - 2, 0));
break;
case 2:
top.t2 = temp;

top.ret = top.t1 + top.t2;
temp = top.ret;
s.Pop();
break;
}

}
return temp;

}

}