//斐波那契数列求和的非递归算法
//非递归算法利用栈作工具,栈的数据类型
struct Node {
int n,tag;
};
//利用栈作工具,非递归算法
long Fibnacci ( long N )
{
Stack S; Node w; long sum = 0;
do {
while ( N > 1 ) {
w.n = N; w.tag = 1; S.Push (w);
N--;
}
//向左递归到底, 边走边进栈
sum = sum + N;
while ( !S.IsEmpty( ) ) {
S.Pop(w);
if ( w.tag == 1 ) { //改为向右递归
w.tag = 2; S.Push (w);
N = w.n - 2;
break;
}
}
} while ( !S.IsEmpty( ) );
return sum;
}
//非递归算法利用栈作工具,栈的数据类型
struct Node {
int n,tag;
};
//利用栈作工具,非递归算法
long Fibnacci ( long N )
{
Stack S; Node w; long sum = 0;
do {
while ( N > 1 ) {
w.n = N; w.tag = 1; S.Push (w);
N--;
}
//向左递归到底, 边走边进栈
sum = sum + N;
while ( !S.IsEmpty( ) ) {
S.Pop(w);
if ( w.tag == 1 ) { //改为向右递归
w.tag = 2; S.Push (w);
N = w.n - 2;
break;
}
}
} while ( !S.IsEmpty( ) );
return sum;
}